Sha256: 7a30b4923504f02e85ec6ddc1d0b296cf18cf5eb1003486a0b2e68dad1e3b6d6

Contents?: true

Size: 1.61 KB

Versions: 45

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true
module Dato
  module Local
    class JsonApiEntity
      attr_reader :payload, :data_source

      def initialize(payload, data_source)
        @payload = payload
        @data_source = data_source
      end

      def id
        @payload[:id]
      end

      def type
        @payload[:type]
      end

      def ==(other)
        if other.is_a? JsonApiEntity
          id == other.id && type == other.type
        else
          false
        end
      end

      def to_s
        "#<JsonApiEntity id=#{id} type=#{type} payload=#{payload}>"
      end
      alias inspect to_s

      def [](key)
        attributes[key]
      end

      def respond_to_missing?(method, include_private = false)
        if attributes.key?(method) || relationships.key?(method)
          true
        else
          super
        end
      end

      private

      def attributes
        @payload.fetch(:attributes, {})
      end

      def relationships
        @payload.fetch(:relationships, {})
      end

      def dereference_linkage(linkage)
        if linkage.is_a? Array
          linkage.map do |item|
            data_source.find_entity(item[:type], item[:id])
          end
        elsif linkage.is_a? Hash
          data_source.find_entity(linkage[:type], linkage[:id])
        end
      end

      def method_missing(method, *arguments, &block)
        return super unless arguments.empty?

        if attributes.key?(method)
          attributes[method]
        elsif relationships.key?(method)
          dereference_linkage(relationships[method][:data])
        else
          super
        end
      end
    end
  end
end

Version data entries

45 entries across 45 versions & 1 rubygems

Version Path
dato-0.6.9 lib/dato/local/json_api_entity.rb
dato-0.6.8 lib/dato/local/json_api_entity.rb
dato-0.6.7 lib/dato/local/json_api_entity.rb
dato-0.6.6 lib/dato/local/json_api_entity.rb
dato-0.6.5 lib/dato/local/json_api_entity.rb
dato-0.6.3 lib/dato/local/json_api_entity.rb
dato-0.6.3.beta lib/dato/local/json_api_entity.rb
dato-0.6.2 lib/dato/local/json_api_entity.rb
dato-0.6.1 lib/dato/local/json_api_entity.rb
dato-0.6.0 lib/dato/local/json_api_entity.rb
dato-0.5.1 lib/dato/local/json_api_entity.rb
dato-0.5.0 lib/dato/local/json_api_entity.rb
dato-0.4.3 lib/dato/local/json_api_entity.rb
dato-0.4.2 lib/dato/local/json_api_entity.rb
dato-0.4.1 lib/dato/local/json_api_entity.rb
dato-0.4.0 lib/dato/local/json_api_entity.rb
dato-0.3.31 lib/dato/local/json_api_entity.rb
dato-0.4.0.pre lib/dato/local/json_api_entity.rb
dato-0.3.30 lib/dato/local/json_api_entity.rb
dato-0.3.29 lib/dato/local/json_api_entity.rb