Class: Oat::Adapters::JsonAPI

Inherits:
Oat::Adapter show all
Defined in:
lib/oat/adapters/json_api.rb

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ JsonAPI

Returns a new instance of JsonAPI.



7
8
9
10
# File 'lib/oat/adapters/json_api.rb', line 7

def initialize(*args)
  super
  @entities = {}
end

Instance Method Details

#entities(name, collection, serializer_class = nil, &block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/oat/adapters/json_api.rb', line 37

def entities(name, collection, serializer_class = nil, &block)
  link_name = name.to_s.pluralize.to_sym
  data[:links][link_name] = []

  collection.each do |obj|
    @entities[link_name] ||= []
    ent = entity_without_root(obj, serializer_class, &block)
    if ent
      data[:links][link_name] << ent[:id]
      @entities[link_name] << ent
    end
  end
end

#entity(name, obj, serializer_class = nil, &block) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/oat/adapters/json_api.rb', line 28

def entity(name, obj, serializer_class = nil, &block)
  @entities[name.to_s.pluralize.to_sym] ||= []
  ent = entity_without_root(obj, serializer_class, &block)
  if ent
    link name, href: ent[:id]
    @entities[name.to_s.pluralize.to_sym] << ent
  end
end


16
17
18
# File 'lib/oat/adapters/json_api.rb', line 16

def link(rel, opts = {})
  data[:links][rel] = opts[:href]
end

#properties(&block) ⇒ Object



20
21
22
# File 'lib/oat/adapters/json_api.rb', line 20

def properties(&block)
  data.merge! yield_props(&block)
end

#property(key, value) ⇒ Object



24
25
26
# File 'lib/oat/adapters/json_api.rb', line 24

def property(key, value)
  data[key] = value
end

#to_hashObject



51
52
53
54
55
56
# File 'lib/oat/adapters/json_api.rb', line 51

def to_hash
  raise "JSON API entities MUST define a type. Use type 'user' in your serializers" unless root_name
  h = {root_name.pluralize.to_sym => [data]}
  h[:linked] = @entities if @entities.keys.any?
  h
end

#type(*types) ⇒ Object



12
13
14
# File 'lib/oat/adapters/json_api.rb', line 12

def type(*types)
  @root_name = types.first.to_s
end