From f1df3f4a2dc8fed3bc3876f957cb2670a57b2ba8 Mon Sep 17 00:00:00 2001 From: Trevor Hinesley Date: Thu, 21 Jun 2018 15:01:02 -0500 Subject: [PATCH] Added documentation about conditional attributes --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/README.md b/README.md index 4e7eaa4..85926e8 100644 --- a/README.md +++ b/README.md @@ -307,6 +307,32 @@ serializer.serializable_hash Custom attributes and relationships that only receive the resource are still possible by defining the block to only receive one argument. +### Conditional Attributes + +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. + +```ruby +class MovieSerializer + include FastJsonapi::ObjectSerializer + + attributes :name, :year + attribute :release_year, if: Proc.new do |record| + # Release year will only be serialized if it's greater than 1990 + record.release_year > 1990 + end + + attribute :director, if: Proc.new do |record, params| + # The director will be serialized only if the :admin key of params is true + params && params[:admin] == true + end +end + +# ... +current_user = User.find(cookies[:current_user_id]) +serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }}) +serializer.serializable_hash +``` + ### Customizable Options Option | Purpose | Example