Class: JSONAPI::Consumer::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi/consumer/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, response) ⇒ Parser

Returns a new instance of Parser.



5
6
7
8
# File 'lib/jsonapi/consumer/parser.rb', line 5

def initialize(klass, response)
  @klass = klass
  @response = response
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



3
4
5
# File 'lib/jsonapi/consumer/parser.rb', line 3

def klass
  @klass
end

#responseObject (readonly)

Returns the value of attribute response.



3
4
5
# File 'lib/jsonapi/consumer/parser.rb', line 3

def response
  @response
end

Instance Method Details

#_bodyObject



67
68
69
# File 'lib/jsonapi/consumer/parser.rb', line 67

def _body
  response.body.with_indifferent_access
end

#_statusObject



71
72
73
# File 'lib/jsonapi/consumer/parser.rb', line 71

def _status
  reponse.status
end

#associations(item) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/jsonapi/consumer/parser.rb', line 14

def associations(item)
  associations = {}
  item.fetch(:links, {}).each do |assoc_name, ids|
    associations[assoc_name] = if ids.is_a?(Array)
                                 ids.collect {|id| find_linked(assoc_name, id) }
                               else
                                 find_linked(assoc_name, ids)
                               end
  end
  associations
end

#attributes(item) ⇒ Object



10
11
12
# File 'lib/jsonapi/consumer/parser.rb', line 10

def attributes(item)
  item.except(:links)
end

#buildObject



60
61
62
63
64
65
# File 'lib/jsonapi/consumer/parser.rb', line 60

def build
  _body.fetch(klass.json_key, []).collect do |attrs|
    attrs_hash = attributes(attrs).merge(associations(attrs))
    klass.new(attrs_hash)
  end
end

#fetch_linked(assoc_name, id) ⇒ Object



38
39
40
# File 'lib/jsonapi/consumer/parser.rb', line 38

def fetch_linked(assoc_name, id)
  klass._association_class_name(assoc_name).find(id)
end

#fetch_resourceObject



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/jsonapi/consumer/parser.rb', line 26

def fetch_resource
  link_body = _body.fetch(:links, {})

  links = {}

  link_body.each do |key, url|
    links[key.split('.').last] = url
  end

  links
end

#find_linked(assoc_name, id) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/jsonapi/consumer/parser.rb', line 42

def find_linked(assoc_name, id)
  if found = linked.fetch(assoc_name.pluralize, []).detect {|h| h.fetch(:id) == id }
    klass._association_class_name(assoc_name).new(found)
  else
    fetch_linked(assoc_name, id)
  end
end

#linkedObject



50
51
52
53
54
55
56
57
58
# File 'lib/jsonapi/consumer/parser.rb', line 50

def linked
  linked_body = _body.fetch(:linked, {})

  linked = {}
  linked_body.each do |key, obj_attrs|
    linked[key] = obj_attrs
  end
  linked
end