Henley Chiu Henley Chiu - 3 months ago 17
Ruby Question

Ruby JBuilder with variable names?

How do I use a variable name when constructing a JSON using

jBuilder
in Ruby?

For example, suppose I have a variable
var1
:

var1 = "query_string"
query = Jbuilder.encode do |json|
json.query do
json.query_string do
json.query "SOMETHING"
end
end
end


How can I do something like:

json.var1 do


Rather than explicitly:
json.query_string
?

Answer

In order to send a message whose name is not statically known, you can use the Object#public_send method:

var1 = 'query_string'

query = Jbuilder.encode do |json|
  json.query do
    json.public_send(var1) do
      json.query "SOMETHING"
    end
  end
end