You are actually calling x.type
and o.type.singularize
instead of calling x.murders
and o.murder
.
Since Nokogiri works by utilizing method_missing
, I believe you should use x.send
instead:
["murders", "mysteries", "thrillers"].each do |type|
define_method("#{type}_xml") do |dir, items, o|
x.send(type) {
items.values.each do |i|
o.send(type.singularize) {
o.classification i[1].to_s
o.titles i[2]
o.path "#{dir}/#{i[3]}.pdf"
}
end
}
end
When you want to call a method dynamically you cannot simply put the variable name as a method name, and hope it will be called:
a = 'to_i'
'123'.a # <= ERROR - _not_ '123'.to_i
Ruby's send API enables you to do that, by passing the method name as an argument:
Invokes the method identified by symbol, passing it any arguments specified. You can use
__send__
if the name send clashes with an existing method in obj. When the method is identified by a string, the string is converted to a symbol.
a = 'to_i'
'123'.send(a) # => 123