dewski / json_builder

Rails provides an excellent XML Builder by default to build RSS and ATOM feeds, but nothing to help you build complex and custom JSON data structures. JSON Builder is here to help.
http://garrettbjerkhoel.com/json_builder/
MIT License
244 stars 52 forks source link

using if statements in view #32

Open ckhall opened 12 years ago

ckhall commented 12 years ago

I have a situation where, based upon certain parameters, I would include certain parts of the object in the response, but it seems this cannot be done with json_builder.

ex:

foos @foos do |foo|
  ...
  # can't do this
  if @opts[include_bars]
    things foo.bars do |bar|
      ...
    end
  end
end
daxhuiberts commented 11 years ago

It seems that the last expression in the block (the return value) is used to decide what value 'foos' will be. If the return statement is the result of one of json_builder's attributes, it knows how to handle that. If it is any other value, it ignores any uses of json_builder's attributes inside the block and use the return value as the value which called the block.

In case of an if statement. When it's true, the if statement's return value is the last expression of the if block, most likely a json_builder attribute. When it's false, the return value is nil and that return value is used for the outer block.

This is a tough problem to fix. In the mean time I use a mock value after the if statement, something like foo 'bar' to make sure to prevent the above problem from occurring.

dewski commented 11 years ago

Good catch here. I'll look into it. In the meantime you could just move the conditional above any members that are always going to be returned.

From:

foo do
  bar true
  if false
    baz true
  end
end

To:

foo do
  if false
    baz true
  end
  bar true
end
alexisraca commented 10 years ago

please fix this