Class: SimpleJsonApi::ResourceSerializer

Inherits:
Serializer
  • Object
show all
Defined in:
lib/simple_json_api/resource_serializer.rb

Overview

The Serializer will serialize a model

Instance Attribute Summary

Attributes inherited from Serializer

#_builder, #_each_serializer, #_object

Attributes included from DSL

#_attributes, #_default_fields, #_required_associations

Instance Method Summary collapse

Methods inherited from Serializer

#associated_object, for, for_polymorphic, for_regular, includes, #initialize, register_serializer

Methods included from DSL

#attribute, #belongs_to, #default_attributes, #default_fields, #has_many, #has_one, #inherited, #required_associations, #serializes

Constructor Details

This class inherits a constructor from SimpleJsonApi::Serializer

Instance Method Details

#_associationsObject



65
66
67
# File 'lib/simple_json_api/resource_serializer.rb', line 65

def _associations
  self.class._associations
end

#_fieldsObject



23
24
25
# File 'lib/simple_json_api/resource_serializer.rb', line 23

def _fields
  @_fields ||= _get_fields
end

#_get_fieldsObject

If default_fields is not specified, use all_fields



28
29
30
# File 'lib/simple_json_api/resource_serializer.rb', line 28

def _get_fields
  builder_fields
end

#_root_nameObject



11
12
13
# File 'lib/simple_json_api/resource_serializer.rb', line 11

def _root_name
  self.class._root_name
end

#attribute_values(hash) ⇒ Object



39
40
41
42
43
44
# File 'lib/simple_json_api/resource_serializer.rb', line 39

def attribute_values(hash)
  _fields.each do |attribute, _attr_opts|
    hash[attribute] = send(attribute).to_s
  end
  hash[:href] = href if self.class.method_defined? :href
end

#idObject



19
20
21
# File 'lib/simple_json_api/resource_serializer.rb', line 19

def id
  _object.try(:id) || _object.try(:guid)
end


52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/simple_json_api/resource_serializer.rb', line 52

def link(association)
  if association.type == :has_many
    includes = association.polymorphic ? [] : Serializer.includes(association)
    resource = send(association.name, includes)
    resource.map do |obj|
      association[:polymorphic] ? obj.typed_json_id : obj.json_id
    end
  else
    resource = send(association.name)
    resource.json_id if resource
  end
end


46
47
48
49
50
# File 'lib/simple_json_api/resource_serializer.rb', line 46

def link_values(root)
  self.class._associations.each do |association|
    root[association.key] = link(association)
  end
end

#serializeObject



32
33
34
35
36
37
# File 'lib/simple_json_api/resource_serializer.rb', line 32

def serialize
  hash = {}
  attribute_values(hash)
  link_values(hash[:links] = {})
  Resource.new(hash)
end

#typeObject



15
16
17
# File 'lib/simple_json_api/resource_serializer.rb', line 15

def type
  _root_name
end