views:

49

answers:

2

Now I know how to build xml without escaping values. http://stackoverflow.com/questions/2693036/how-to-tell-bulider-to-not-to-escape-values

However I need to build tags dynamically.

Desired result

<bank_info>Chase</bank_info>

What I have is

attr = 'bank_info'
builder = Builder::XmlMarkup.new
builder.attr { |x| x << 'bank_info' } # does not work

I can try making the whole thing as a giant string and eval that. But evaling is not that safe. Is there a better option that I am missing.

+1  A: 

In general, the simplest way to call a method for which you have a name is to use send or __send__. Here:

builder = Builder::XmlMarkup.new
builder.__send__("bank_info") do  # same effect as:  builder.bank_info do
  builder << "Chase"
end

BTW, there is the variant public_send, in case you want to insure you are not calling a private method. Tu use it, you must require "backports" if using Ruby 1.8.

Note: in this case, send doesn't work, as pointed out by KandadaBoggu, because Builder overrides it; you must use __send__.

Marc-André Lafortune
@marc Your code will generate `<send>bank_infoChase</send>` as markup. It looks like builder is overriding all the default methods. I worked around it by using `tag!` method.
KandadaBoggu
That should teach me not to test my code! I wonder if `__send__` is also overriden... Anyways, `tag!` is the way to go
Marc-André Lafortune
sorry I should have mentioned that I want my data to be unescaped and tag! escapes it. That is why in my example I resorted to << .
Nadal
Ah, so I checked and `__send__` is what you want to use. Answer updated
Marc-André Lafortune
that's awesome. Thanks.
Nadal
+1  A: 

Try this:

 builder.tag! "bank_info", "Citi"
KandadaBoggu
sorry I should have mentioned that I want my data to be unescaped and tag! escapes it. That is why in my example I resorted to << .
Nadal