Class: JsonApiClient::LinkedData

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/json_api_client/linked_data.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, link_definition, record_class) ⇒ LinkedData

Returns a new instance of LinkedData.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/json_api_client/linked_data.rb', line 11

def initialize(data, link_definition, record_class)
  @link_definition = link_definition
  @record_class = record_class
  @results_by_type_by_id = {}

  data.each do |type, results|
    klass = klass_for(type)
    add_data(type, results.map{|result| klass.new(result)})
  end

  @results_by_type_by_id.values.each do |results|
    results.values.each do |result|
      result.linked_data = self
    end
  end
end

Instance Attribute Details

Returns the value of attribute link_definition.



5
6
7
# File 'lib/json_api_client/linked_data.rb', line 5

def link_definition
  @link_definition
end

#record_classObject (readonly)

Returns the value of attribute record_class.



5
6
7
# File 'lib/json_api_client/linked_data.rb', line 5

def record_class
  @record_class
end

Instance Method Details

#add_data(key, data) ⇒ Object



65
66
67
68
# File 'lib/json_api_client/linked_data.rb', line 65

def add_data(key, data)
  @results_by_type_by_id[key] ||= {}
  @results_by_type_by_id[key].merge!(data.index_by{|datum| datum["id"]})
end

#data_for(type, ids) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/json_api_client/linked_data.rb', line 28

def data_for(type, ids)
  ids = Array(ids)

  # the name of the linked data is provided by the link definition from the result
  attr_name = link_definition.attribute_name_for(type)

  # get any preloaded data from the result
  type_data = @results_by_type_by_id.fetch(attr_name, {})

  # find the associated class for the data
  klass = klass_for(type)

  # return all the found records
  found, missing = ids.partition { |id| type_data[id].present? }

  # make another api request if there are missing records
  fetch_data(klass, type, missing) if missing.present?

  # reload data
  type_data = @results_by_type_by_id.fetch(attr_name, {})

  ids.map do |id|
    type_data[id]
  end
end

#fetch_data(klass, type, missing_ids) ⇒ Object

make an api request to fetch the missing data



55
56
57
58
59
60
61
62
63
# File 'lib/json_api_client/linked_data.rb', line 55

def fetch_data(klass, type, missing_ids)
  path = URI(link_definition.url_for(type, missing_ids)).path

  query = Query::Linked.new(path)
  results = klass.run_request(query)

  key = link_definition.attribute_name_for(type).to_s
  add_data(key, results)
end

#klass_for(type) ⇒ Object



70
71
72
# File 'lib/json_api_client/linked_data.rb', line 70

def klass_for(type)
  Utils.compute_type(record_class, type.to_s.pluralize.classify)
end