Skip to content

Commit f1df3f4

Browse files
TrevorHinesleyshishirmk
authored andcommitted
Added documentation about conditional attributes
1 parent bad004f commit f1df3f4

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

README.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,32 @@ serializer.serializable_hash
307307
Custom attributes and relationships that only receive the resource are still possible by defining
308308
the block to only receive one argument.
309309

310+
### Conditional Attributes
311+
312+
Conditional attributes can be defined by passing a Proc to the `if` key on the `attribute` method. Return `true` if the attribute should be serialized, and `false` if not. The record and any params passed to the serializer are available inside the Proc as the first and second parameters, respectively.
313+
314+
```ruby
315+
class MovieSerializer
316+
include FastJsonapi::ObjectSerializer
317+
318+
attributes :name, :year
319+
attribute :release_year, if: Proc.new do |record|
320+
# Release year will only be serialized if it's greater than 1990
321+
record.release_year > 1990
322+
end
323+
324+
attribute :director, if: Proc.new do |record, params|
325+
# The director will be serialized only if the :admin key of params is true
326+
params && params[:admin] == true
327+
end
328+
end
329+
330+
# ...
331+
current_user = User.find(cookies[:current_user_id])
332+
serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})
333+
serializer.serializable_hash
334+
```
335+
310336
### Customizable Options
311337

312338
Option | Purpose | Example

0 commit comments

Comments
 (0)