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.



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

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

Instance Method Details

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



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/oat/adapters/json_api.rb', line 44

def entities(name, collection, serializer_class = nil, context_options = {}, &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, context_options, &block)
    if ent
      data[:links][link_name] << ent[:id]
      @entities[link_name] << ent
    end
  end
end

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



35
36
37
38
39
40
41
42
# File 'lib/oat/adapters/json_api.rb', line 35

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


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

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

#properties(&block) ⇒ Object



27
28
29
# File 'lib/oat/adapters/json_api.rb', line 27

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

#property(key, value) ⇒ Object



31
32
33
# File 'lib/oat/adapters/json_api.rb', line 31

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

#to_hash ⇒ Object



58
59
60
61
62
63
# File 'lib/oat/adapters/json_api.rb', line 58

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



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

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