Sha256: bf43648937c268375e775db9b11fc7333043e843ecdeb87dde81a07b58c57dcb

Contents?: true

Size: 1.21 KB

Versions: 2

Compression:

Stored size: 1.21 KB

Contents

module JsonApiClient
  module Helpers
    module Relatable
      extend ActiveSupport::Concern

      included do
        class_attribute :relationship_linker
        self.relationship_linker = Relationships::Relations

        # the relationships for this resource
        attr_accessor :relationships

        initializer do |obj, params|
          relationships = params && params.delete("relationships")
          relationships ||= {}
          obj.relationships = obj.relationship_linker.new(relationships)
        end
      end

      def as_relation
        {
          :type => self.class.table_name,
          primary_key => self[primary_key]
        }
      end

      def attributes
        super.tap do |attrs|
          attrs.merge!(relationships: relationships.attributes) if relationships.present?
        end
      end

      def method_missing(method, *args)
        return super unless relationships and relationships.has_attribute?(method) and result_set.included
        result_set.included.data_for(method, relationships[method])
      end

      def respond_to_missing?(symbol, include_all = false)
        return true if relationships && relationships.has_attribute?(symbol)
        super
      end

    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
json_api_client-1.0.0.beta3 lib/json_api_client/helpers/relatable.rb
json_api_client-1.0.0.beta2 lib/json_api_client/helpers/relatable.rb