Module: JsonapiCompliable::Extensions::ExtraAttribute

Defined in:
lib/jsonapi_compliable/extensions/extra_attribute.rb

Overview

Only render a given attribute when the user specifically requests it. Useful for computationally-expensive attributes that are not required on every request.

This class handles the serialization, but you may also want to run code during scoping (for instance, to eager load associations referenced by this extra attribute. See (Resource.extra_field).

Examples:

Basic Usage

# Will only be rendered on user request, ie
# /people?extra_fields[people]=net_worth
extra_attribute :net_worth

Eager Loading

class PersonResource < ApplicationResource
  # If the user requests the 'net_worth' attribute, make sure
  # 'assets' are eager loaded
  extra_field :net_worth do |scope|
    scope.includes(:assets)
  end
end

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

See Also:

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



36
37
38
# File 'lib/jsonapi_compliable/extensions/extra_attribute.rb', line 36

def self.included(klass)
  klass.extend ClassMethods
end