Reputation: 22515
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
?
Upvotes: 3
Views: 1848
Reputation: 138
You can alternatively use set!
method.
jbuider's docs on github gives this example:
json.set! :author do
json.set! :name, 'David'
end
# => {"author": { "name": "David" }}
For your example, it would be something like:
var1 = "query_string"
query = Jbuilder.encode do |json|
json.query do
json.set! var1 do
json.query "SOMETHING"
end
end
end
Upvotes: 7
Reputation: 369468
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
Upvotes: 1