json_builder icon indicating copy to clipboard operation
json_builder copied to clipboard

using if statements in view

Open ckhall opened this issue 13 years ago • 3 comments

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

ckhall avatar Jul 31 '12 15:07 ckhall

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.

daxhuiberts avatar Sep 19 '12 09:09 daxhuiberts

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

dewski avatar Sep 27 '12 06:09 dewski

please fix this

alexisraca avatar Jun 27 '14 15:06 alexisraca