Module: JsonapiSerializer::Base

Extended by:
ActiveSupport::Concern
Includes:
Common, DSL::Common, Utils
Defined in:
lib/jsonapi_serializer/base.rb

Instance Method Summary collapse

Methods included from Common

#serializable_hash, #serialized_json, #type

Methods included from Utils

#apply_splat, #key_intersect, #normalize_includes

Instance Method Details

#attributes_hash(record) ⇒ Object



31
32
33
34
35
# File 'lib/jsonapi_serializer/base.rb', line 31

def attributes_hash(record)
  @attributes.each_with_object({}) do |(key, val), hash|
    hash[key] = val.call(record)
  end
end

#id_hash(record) ⇒ Object



27
28
29
# File 'lib/jsonapi_serializer/base.rb', line 27

def id_hash(record)
  {id: @id.call(record), type: @type}
end

#initialize(opts = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/jsonapi_serializer/base.rb', line 14

def initialize(opts = {})
  super(opts)
  @id = self.class.meta_id
  unless opts[:id_only]
    @attributes = []
    @relationships = []
    @includes = normalize_includes(opts.fetch(:include, []))
    prepare_fields(opts)
    prepare_attributes
    prepare_relationships
  end
end

#record_hash(record, context = {}) ⇒ Object



58
59
60
61
62
63
64
65
66
# File 'lib/jsonapi_serializer/base.rb', line 58

def record_hash(record, context = {})
  hash = id_hash(record)
  if context[:tracker]
    (context[:tracker][hash[:type]] ||= Set.new).add?(hash[:id])
  end
  hash[:attributes] = attributes_hash(record) if @attributes.present?
  hash[:relationships] = relationships_hash(record, context) if @relationships.present?
  hash
end

#relationships_hash(record, context = {}) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/jsonapi_serializer/base.rb', line 37

def relationships_hash(record, context = {})
  @relationships.each_with_object({}) do |(key, type, from, serializer), hash|
    if rel = record.public_send(from)
      if rel.respond_to?(:each)
        hash[key] = {data: []}
        rel.each do |item|
          id = serializer.id_hash(item)
          hash[key][:data] << id
          add_included(serializer, item, id, context) if @includes.has_key?(key)
        end
      else
        id = serializer.id_hash(rel)
        hash[key] = {data: id}
        add_included(serializer, rel, id, context) if @includes.has_key?(key)
      end
    else
      hash[key] = {data: nil}
    end
  end
end