Henley Wing Chiu
Henley Wing Chiu

Reputation: 22515

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?

Upvotes: 3

Views: 1848

Answers (2)

Ahmad Saleem
Ahmad Saleem

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

Jörg W Mittag
Jörg W Mittag

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

Related Questions