From 01bdb33a4ea652d1c17bdf1695f35f8675e7c34a Mon Sep 17 00:00:00 2001 From: Andrew Rempe Date: Tue, 15 Nov 2016 16:31:27 -0500 Subject: [PATCH] Fix nil values causing errors when merge option passed --- CHANGELOG.md | 1 + .../exposure/nesting_exposure/output_builder.rb | 1 + spec/grape_entity/entity_spec.rb | 12 ++++++++++++ 3 files changed, 14 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f5d6479..e356b0e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ #### Fixes +* [#248](https://github.com/ruby-grape/grape-entity/pull/248): Fix `nil` values causing errors when `merge` option passed - [@arempe93](https://github.com/arempe93). * Your contribution here. ### 0.5.2 (2016-11-14) diff --git a/lib/grape_entity/exposure/nesting_exposure/output_builder.rb b/lib/grape_entity/exposure/nesting_exposure/output_builder.rb index 5fc4a63b..66f77a43 100644 --- a/lib/grape_entity/exposure/nesting_exposure/output_builder.rb +++ b/lib/grape_entity/exposure/nesting_exposure/output_builder.rb @@ -17,6 +17,7 @@ def add(exposure, result) # If we have an array which should not be merged - save it with a key as a hash # If we have hash which should be merged - save it without a key (merge) if exposure.for_merge + return unless result @output_hash.merge! result, &merge_strategy(exposure.for_merge) else @output_hash[exposure.key] = result diff --git a/spec/grape_entity/entity_spec.rb b/spec/grape_entity/entity_spec.rb index 12553de6..d9f5e80f 100644 --- a/spec/grape_entity/entity_spec.rb +++ b/spec/grape_entity/entity_spec.rb @@ -50,6 +50,18 @@ subject.expose(:special, merge: ->(_, v1, v2) { v1 && v2 ? 'brand new val' : v2 }) expect(subject.represent(nested_hash).serializable_hash).to eq(like_nested_hash: 'brand new val') end + + context 'and nested object is nil' do + let(:nested_hash) do + { something: nil, special: { like_nested_hash: '12' } } + end + + it 'adds nothing to output' do + subject.expose(:something, merge: true) + subject.expose(:special) + expect(subject.represent(nested_hash).serializable_hash).to eq(special: { like_nested_hash: '12' }) + end + end end context 'with a block' do