Skip to content

Commit 85220f5

Browse files
committed
Merge pull request #98 from zbelzer/respect_conditions
Respect nested conditions
2 parents 974e47d + b905c1b commit 85220f5

File tree

4 files changed

+27
-3
lines changed

4 files changed

+27
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ Next Release
22
============
33

44
* Your contribution here.
5+
* [#98](https://github.com/intridea/grape-entity/pull/98): Add nested conditionals - [@zbelzer](https://github.com/zbelzer).
56
* [#91](https://github.com/intridea/grape-entity/pull/91): Fix OpenStruct serializing - [@etehtsea](https://github.com/etehtsea).
67

78
0.4.4 (2014-08-17)

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,16 @@ expose :contact_info do
117117
end
118118
```
119119

120+
You can also conditionally expose attributes in nested exposures:
121+
```ruby
122+
expose :contact_info do
123+
expose :phone
124+
expose :address, using: API::Address
125+
expose :email, if: lambda { |instance, options| options[:type] == :full }
126+
end
127+
```
128+
129+
120130
#### Collection Exposure
121131

122132
Use `root(plural, singular = nil)` to expose an object or a collection of objects with a root key.

lib/grape_entity/entity.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -535,10 +535,14 @@ def value_for(attribute, options = {})
535535
end
536536

537537
elsif nested_exposures.any?
538-
Hash[nested_exposures.map do |nested_attribute, _|
539-
[self.class.key_for(nested_attribute), value_for(nested_attribute, options)]
540-
end]
538+
nested_attributes =
539+
nested_exposures.map do |nested_attribute, nested_exposure_options|
540+
if conditions_met?(nested_exposure_options, options)
541+
[self.class.key_for(nested_attribute), value_for(nested_attribute, options)]
542+
end
543+
end
541544

545+
Hash[nested_attributes.compact]
542546
else
543547
delegate_attribute(attribute)
544548
end

spec/grape_entity/entity_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,15 @@ class BogusEntity < Grape::Entity
111111
)
112112
end
113113

114+
it 'does not represent nested exposures whose conditions are not met' do
115+
subject.expose :awesome do
116+
subject.expose(:condition_met, if: lambda { |_, _| true }) { |_| 'value' }
117+
subject.expose(:condition_not_met, if: lambda { |_, _| false }) { |_| 'value' }
118+
end
119+
120+
expect(subject.represent({}).send(:value_for, :awesome)).to eq(condition_met: 'value')
121+
end
122+
114123
it 'does not represent attributes, declared inside nested exposure, outside of it' do
115124
subject.expose :awesome do
116125
subject.expose(:nested) { |_| 'value' }

0 commit comments

Comments
 (0)