Skip to content

Commit

Permalink
Option expose_nil doesn't work when block is passed (#329)
Browse files Browse the repository at this point in the history
* Makes expose_nil option work well with blocks.

* Updated CHANGELOG.md

Co-authored-by: peter scholz <pscholz.le@gmail.com>
  • Loading branch information
serbiant and LeFnord committed Feb 17, 2020
1 parent 54f68b2 commit 96afd88
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -10,6 +10,7 @@
#### Fixes

* Your contribution here.
* [#329](https://github.com/ruby-grape/grape-entity/pull/329): Option expose_nil doesn't work when block is passed - [@serbiant](https://github.com/serbiant).
* [#320](https://github.com/ruby-grape/grape-entity/pull/320): Gemspec: drop eol'd property rubyforge_project - [@olleolleolle](https://github.com/olleolleolle).
* [#307](https://github.com/ruby-grape/grape-entity/pull/307): Allow exposures to call methods defined in modules included in an entity - [@robertoz-01](https://github.com/robertoz-01).

Expand Down
12 changes: 9 additions & 3 deletions lib/grape_entity/exposure.rb
Expand Up @@ -47,14 +47,20 @@ def compile_conditions(attribute, options)
options[:unless]
].compact.flatten.map { |cond| Condition.new_unless(cond) }

unless_conditions << expose_nil_condition(attribute) if options[:expose_nil] == false
unless_conditions << expose_nil_condition(attribute, options) if options[:expose_nil] == false

if_conditions + unless_conditions
end

def expose_nil_condition(attribute)
def expose_nil_condition(attribute, options)
Condition.new_unless(
proc { |object, _options| Delegator.new(object).delegate(attribute).nil? }
proc do |object, _options|
if options[:proc].nil?
Delegator.new(object).delegate(attribute).nil?
else
exec_with_object(options, &options[:proc]).nil?
end
end
)
end

Expand Down
20 changes: 20 additions & 0 deletions spec/grape_entity/entity_spec.rb
Expand Up @@ -126,6 +126,26 @@ def initialize(a, b, c)
expect { subject.expose(:a, :b, :c, expose_nil: false) }.to raise_error ArgumentError
end
end

context 'when expose_nil option is false and block passed' do
it 'does not expose if block returns nil' do
subject.expose(:a, expose_nil: false) do |_obj, _options|
nil
end
subject.expose(:b)
subject.expose(:c)
expect(subject.represent(model).serializable_hash).to eq(b: nil, c: 'value')
end

it 'exposes is block returns a value' do
subject.expose(:a, expose_nil: false) do |_obj, _options|
100
end
subject.expose(:b)
subject.expose(:c)
expect(subject.represent(model).serializable_hash).to eq(a: 100, b: nil, c: 'value')
end
end
end

context 'when model is a hash' do
Expand Down

0 comments on commit 96afd88

Please sign in to comment.