File tree Expand file tree Collapse file tree 4 files changed +27
-3
lines changed Expand file tree Collapse file tree 4 files changed +27
-3
lines changed Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ Next Release
2
2
============
3
3
4
4
* Your contribution here.
5
+ * [ #98 ] ( https://github.com/intridea/grape-entity/pull/98 ) : Add nested conditionals - [ @zbelzer ] ( https://github.com/zbelzer ) .
5
6
* [ #91 ] ( https://github.com/intridea/grape-entity/pull/91 ) : Fix OpenStruct serializing - [ @etehtsea ] ( https://github.com/etehtsea ) .
6
7
7
8
0.4.4 (2014-08-17)
Original file line number Diff line number Diff line change @@ -117,6 +117,16 @@ expose :contact_info do
117
117
end
118
118
```
119
119
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
+
120
130
#### Collection Exposure
121
131
122
132
Use ` root(plural, singular = nil) ` to expose an object or a collection of objects with a root key.
Original file line number Diff line number Diff line change @@ -535,10 +535,14 @@ def value_for(attribute, options = {})
535
535
end
536
536
537
537
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
541
544
545
+ Hash [ nested_attributes . compact ]
542
546
else
543
547
delegate_attribute ( attribute )
544
548
end
Original file line number Diff line number Diff line change @@ -111,6 +111,15 @@ class BogusEntity < Grape::Entity
111
111
)
112
112
end
113
113
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
+
114
123
it 'does not represent attributes, declared inside nested exposure, outside of it' do
115
124
subject . expose :awesome do
116
125
subject . expose ( :nested ) { |_ | 'value' }
You can’t perform that action at this time.
0 commit comments