Skip to content

Commit 9823f41

Browse files
committed
explain how to pass option to nested exposure
add a new section to explain how to pass additional option to nested expose and show how to retrieve new option in nested exposure
1 parent 00328f1 commit 9823f41

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

README.md

+24
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,30 @@ end
305305
present s, with: Status, user: current_user
306306
```
307307

308+
#### Passing Additional Option To Nested Exposure
309+
There are sometimes that you want to pass additional option or parameter to nested exposure. Assume that you need to expose an address for a contact info, but it has both two different format: **full** and **simple**. You can pass an additional `full_format` option to specify that if the nested entity should render address in `:full` format.
310+
311+
```ruby
312+
# api/contact.rb
313+
expose :contact_info do
314+
expose :phone
315+
expose :address do |instance, options|
316+
# use `#merge` to extend options and then pass the new version of options to the nested entity
317+
API::Address.represent instance.address, options.merge(full_format: instance.need_full_format?)
318+
end
319+
expose :email, if: lambda { |instance, options| options[:type] == :full }
320+
end
321+
322+
# api/address.rb
323+
expose :state, if: lambda {|instance, options| !!options[:full_format]} # the new option could be retrieved in options hash for conditional exposure
324+
expose :city, if: lambda {|instance, options| !!options[:full_format]}
325+
expose :stree do |instance, options|
326+
# the new option could be retrieved in options hash for runtime exposure
327+
!!options[:full_format] ? instance.full_street_name : instance.simple_street_name
328+
end
329+
```
330+
**Notice**: In the above code, you should pay attention to [**Safe Exposure**](#safe-exposure) yourself, for example, `instance.address` might be `nil`, in this situation, it is better to expose it as nil directly.
331+
308332
### Using the Exposure DSL
309333

310334
Grape ships with a DSL to easily define entities within the context of an existing class:

0 commit comments

Comments
 (0)