Class: JsonApiClient::IncludedData

Inherits:
Object
  • Object
show all
Defined in:
lib/json_api_client/included_data.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(result_set, data) ⇒ IncludedData

Returns a new instance of IncludedData.


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/json_api_client/included_data.rb', line 5

def initialize(result_set, data)
  record_class = result_set.record_class
  grouped_data = data.group_by{|datum| datum["type"]}
  grouped_included_set = grouped_data.each_with_object({}) do |(type, records), h|
    klass = Utils.compute_type(record_class, record_class.key_formatter.unformat(type).singularize.classify)
    h[type] = records.map do |record|
      params = klass.parser.parameters_from_resource(record)
      klass.load(params).tap do |resource|
        resource.last_result_set = result_set
      end
    end
  end

  if record_class.search_included_in_result_set
    # deep_merge overrides the nested Arrays o_O
    # {a: [1,2]}.deep_merge(a: [3,4]) # => {a: [3,4]}
    grouped_included_set.merge!(result_set.group_by(&:type)) do |_, resources1, resources2|
      resources1 + resources2
    end
  end

  grouped_included_set.each do |type, resources|
    grouped_included_set[type] = resources.index_by(&:id)
  end

  @data = grouped_included_set
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data


3
4
5
# File 'lib/json_api_client/included_data.rb', line 3

def data
  @data
end

Instance Method Details

#data_for(method_name, definition) ⇒ Object


33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/json_api_client/included_data.rb', line 33

def data_for(method_name, definition)
  # If data is defined, pull the record from the included data
  return nil unless data = definition["data"]

  if data.is_a?(Array)
    # has_many link
    data.map(&method(:record_for)).compact
  else
    # has_one link
    record_for(data)
  end
end

#has_link?(name) ⇒ Boolean

Returns:

  • (Boolean)

46
47
48
# File 'lib/json_api_client/included_data.rb', line 46

def has_link?(name)
  data.has_key?(name.to_s)
end