Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

expose_nil: conflicts with options passing to a block #378

Closed
zverok opened this issue Aug 16, 2023 · 0 comments · Fixed by #381
Closed

expose_nil: conflicts with options passing to a block #378

zverok opened this issue Aug 16, 2023 · 0 comments · Fixed by #381

Comments

@zverok
Copy link

zverok commented Aug 16, 2023

Minimum reproducible example:

class Test < Grape::Entity
  expose(:a, expose_nil: false) { |obj, options| options[:a] }
end

pp Test.new({}, a: 1).as_json # expected {a: 1}, renders {}
pp Test.new({}, a: nil).as_json # expected {}, renders {}

More debugging shows that block always returns nil, because when expose_nil: is present, the content of options inside block is changed completely; which this debugging serializer shows:

class Test < Grape::Entity
   expose(:a) { |obj, options| p(simple: options); options[:a] }
   expose(:b, as: :d) { |obj, options| p(with_as: options); obj[:a] }

   expose(:c, expose_nil: false) { |obj, options| p(with_expose_nil: options); options[:a] }
end

pp Test.new({}, a: 1, b: 2, c: 3).as_json

It prints this values for options inside blocks (and yes, in this order):

{:with_expose_nil=>{:expose_nil=>false, :proc=>#<Proc:0x0000555bb661d9a8 test_grape_expose.rb:52>}}
{:simple=>#<Grape::Entity::Options:0x0000555bb661c210 @opts_hash={:a=>1, :b=>2, :c=>3, :attr_path=>[:a]}, @has_only=false, @has_except=false, @for_nesting_cache={}, @should_return_key_cache={}>}
{:with_as=>#<Grape::Entity::Options:0x0000555bb661c210 @opts_hash={:a=>1, :b=>2, :c=>3, :attr_path=>[:d]}, @has_only=false, @has_except=false, @for_nesting_cache={}, @should_return_key_cache={}>}

It seems that block in this case receives "options passed to expose DSL" instead of "options passed to serialization"?..

magni- added a commit to magni-/grape-entity that referenced this issue Dec 13, 2023
magni- added a commit to magni-/grape-entity that referenced this issue Dec 13, 2023
LeFnord pushed a commit that referenced this issue Dec 13, 2023
…e using a block (#381)

* Pass the right options when determining whether to expose an attribute using a block

Fixes #378

* Autocorrect Rubocop offenses
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant