Skip to content
This repository has been archived by the owner on Jan 30, 2019. It is now read-only.

using if statements in view #32

Open
ckhall opened this issue Jul 31, 2012 · 3 comments
Open

using if statements in view #32

ckhall opened this issue Jul 31, 2012 · 3 comments

Comments

@ckhall
Copy link

ckhall commented Jul 31, 2012

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
Copy link

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
Copy link
Owner

dewski commented Sep 27, 2012

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
Copy link

please fix this

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants