Class: MetaModel::MetaModel

Inherits:
ActiveModelSerializers::Model
  • Object
show all
Defined in:
lib/meta_model/meta_model.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(jsonapi_resource, index = nil) ⇒ MetaModel

Returns a new instance of MetaModel.



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/meta_model/meta_model.rb', line 6

def initialize(jsonapi_resource, index = nil)
  @jsonapi_resource = jsonapi_resource
  @type = jsonapi_resource[:data][:type]
  @id = jsonapi_resource[:data][:id]
  @attributes = jsonapi_resource[:data][:attributes] || {}
  @relationships = jsonapi_resource[:data][:relationships] || []
  @included = jsonapi_resource[:included] || []
  @index = index || Hash.new
  index_includes
  set_attributes if @attributes.size > 0
  populate_relationships if @relationships.size > 0
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



4
5
6
# File 'lib/meta_model/meta_model.rb', line 4

def id
  @id
end

#typeObject (readonly)

Returns the value of attribute type.



4
5
6
# File 'lib/meta_model/meta_model.rb', line 4

def type
  @type
end

Instance Method Details

#setup_serializer(serializer) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/meta_model/meta_model.rb', line 19

def setup_serializer(serializer)
  keys = (@attributes.keys + [:id]).join(', :')
  serializer.singleton_class.class_eval <<-end_eval
  self._attributes_data = {}
  self._reflections = []
  attributes :#{keys}
  end_eval

  @relationships.each do |relationship_name, value|
    relationship = value.is_a?(Array) ? "has_many" : "has_one"
    serializer.singleton_class.class_eval <<-end_eval
    #{relationship} :#{relationship_name}
    def #{relationship_name}
      object.#{relationship_name}
    end
    end_eval
  end
end