Module: JSONAPI::Serializable::Resource::Attributes

Included in:
JSONAPI::Serializable::Resource
Defined in:
lib/jsonapi/serializable/resource/attributes.rb

Overview

Mixin to handle resource attributes.

Defined Under Namespace

Modules: DSL

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.prepended(klass) ⇒ Object



6
7
8
9
10
11
12
13
14
15
# File 'lib/jsonapi/serializable/resource/attributes.rb', line 6

def self.prepended(klass)
  super
  klass.class_eval do
    extend DSL
    class << self
      attr_accessor :attribute_blocks
    end
    self.attribute_blocks = {}
  end
end

Instance Method Details

#as_jsonapi(fields: nil, include: []) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/jsonapi/serializable/resource/attributes.rb', line 23

def as_jsonapi(fields: nil, include: [])
  super.tap do |hash|
    attrs =
      requested_attributes(fields).each_with_object({}) do |(k, v), h|
        h[k] = instance_eval(&v)
      end
    hash[:attributes] = attrs if attrs.any?
  end
end

#initializeObject



17
18
19
20
# File 'lib/jsonapi/serializable/resource/attributes.rb', line 17

def initialize(*)
  super
  @_attributes = {}
end

#requested_attributes(fields) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



34
35
36
37
# File 'lib/jsonapi/serializable/resource/attributes.rb', line 34

def requested_attributes(fields)
  self.class.attribute_blocks
      .select { |k, _| fields.nil? || fields.include?(k) }
end