Class: JsonapiCompliable::Scoping::ExtraFields

Inherits:
Base
  • Object
show all
Defined in:
lib/jsonapi_compliable/scoping/extra_fields.rb

Overview

Apply logic when an extra field is requested. Useful for eager loading associations used to compute the extra field.

Given a Resource

class PersonResource < ApplicationResource
  extra_field :net_worth do |scope|
    scope.includes(:assets)
  end
end

And a corresponding serializer:

class SerializablePerson < JSONAPI::Serializable::Resource
  extra_attribute :net_worth do
    @object.assets.sum(&:value)
  end
end

When the user requests the extra field 'net_worth':

GET /people?extra_fields[people]=net_worth

The assets will be eager loaded and the 'net_worth' attribute will be present in the response. If this field is not explicitly requested, none of this logic fires.

Instance Attribute Summary

Attributes inherited from Base

#query_hash, #resource

Instance Method Summary collapse

Methods inherited from Base

#apply?, #apply_custom_scope, #apply_standard_scope, #initialize

Constructor Details

This class inherits a constructor from JsonapiCompliable::Scoping::Base

Instance Method Details

#applyObject

Loop through all requested extra fields. If custom scoping logic is define for that field, run it. Otherwise, do nothing.

Returns:

  • the scope object we are chaining/modofying



36
37
38
39
40
41
42
# File 'lib/jsonapi_compliable/scoping/extra_fields.rb', line 36

def apply
  each_extra_field do |callable|
    @scope = callable.call(@scope)
  end

  @scope
end