Sha256: 6d41a157eb58358adb565dbfdce85ac9e6b13755e7178e00cfff3adeb139c5f6

Contents?: true

Size: 1.29 KB

Versions: 11

Compression:

Stored size: 1.29 KB

Contents

module JsonApiClient
  module Relationships
    class Relations
      include Helpers::DynamicAttributes
      include Helpers::Dirty
      include ActiveModel::Serialization

      attr_reader :record_class
      delegate :key_formatter, to: :record_class

      def initialize(record_class, relations)
        @record_class = record_class
        self.attributes = relations
        clear_changes_information
      end

      def present?
        attributes.present?
      end

      def as_json_api
        Hash[attributes_for_serialization.map do |k, v|
               [k, v.slice("data")]  if v.has_key?("data")
             end.compact]
      end

      def as_json
        Hash[attributes.map do |k, v|
               [k, v.slice("data")]  if v.has_key?("data")
             end.compact]
      end

      def attributes_for_serialization
        attributes.slice(*changed)
      end

      protected

      def set_attribute(name, value)
        value = case value
        when JsonApiClient::Resource
          {data: value.as_relation}
        when Array
          {data: value.map(&:as_relation)}
        when NilClass
          {data: nil}
        else
          value
        end
        attribute_will_change!(name) if value != attributes[name]
        attributes[name] = value
      end

    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
json_api_client-1.6.4 lib/json_api_client/relationships/relations.rb
json_api_client-1.6.3 lib/json_api_client/relationships/relations.rb
json_api_client-1.6.2 lib/json_api_client/relationships/relations.rb
json_api_client-1.6.1 lib/json_api_client/relationships/relations.rb
json_api_client-1.6.0 lib/json_api_client/relationships/relations.rb
json_api_client-1.5.3 lib/json_api_client/relationships/relations.rb
json_api_client-1.5.2 lib/json_api_client/relationships/relations.rb
json_api_client-1.5.1 lib/json_api_client/relationships/relations.rb
json_api_client-1.5.0 lib/json_api_client/relationships/relations.rb
json_api_client-1.4.0 lib/json_api_client/relationships/relations.rb
json_api_client-1.3.0 lib/json_api_client/relationships/relations.rb