Sha256: 224b35a37f8e347c48cbc7c7db8fcb7149fc6d3e7f81ede14f63b67d1fed0d49

Contents?: true

Size: 1.23 KB

Versions: 13

Compression:

Stored size: 1.23 KB

Contents

module JsonApiClient
  class IncludedData
    attr_reader :data

    def initialize(result_set, data)
      record_class = result_set.record_class
      grouped_data = data.group_by{|datum| datum["type"]}
      @data = grouped_data.inject({}) do |h, (type, records)|
        klass = Utils.compute_type(record_class, record_class.key_formatter.unformat(type).singularize.classify)
        h[type] = records.map do |datum|
          params = klass.parser.parameters_from_resource(datum)
          resource = klass.load(params)
          resource.last_result_set = result_set
          resource
        end.index_by(&:id)
        h
      end
    end

    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 do |link_def|
          record_for(link_def)
        end
      else
        # has_one link
        record_for(data)
      end
    end

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

    private

    # should return a resource record of some type for this linked document
    def record_for(link_def)
      data[link_def["type"]][link_def["id"]]
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
json_api_client-1.7.0 lib/json_api_client/included_data.rb
json_api_client-1.6.4 lib/json_api_client/included_data.rb
json_api_client-1.6.3 lib/json_api_client/included_data.rb
json_api_client-1.6.2 lib/json_api_client/included_data.rb
json_api_client-1.6.1 lib/json_api_client/included_data.rb
json_api_client-1.6.0 lib/json_api_client/included_data.rb
json_api_client-1.5.3 lib/json_api_client/included_data.rb
json_api_client-1.5.2 lib/json_api_client/included_data.rb
json_api_client-1.5.1 lib/json_api_client/included_data.rb
json_api_client-1.5.0 lib/json_api_client/included_data.rb
json_api_client-1.4.0 lib/json_api_client/included_data.rb
json_api_client-1.3.0 lib/json_api_client/included_data.rb
json_api_client-1.2.0 lib/json_api_client/included_data.rb