Sha256: afa00b1edf9d6bcf3dc9ed8dff57800657b6aa61e5da13eaaf61c01d0b79082c

Contents?: true

Size: 1.93 KB

Versions: 2

Compression:

Stored size: 1.93 KB

Contents

require 'api_resource/associations/association_scope'

module ApiResource
  
  module Associations
    
    class SingleObjectProxy < AssociationScope

      def serializable_hash(options = {})
        return if self.internal_object.nil?
        self.internal_object.serializable_hash(options)
      end

      def internal_object
        unless instance_variable_defined?(:@internal_object)
          if self.remote_path.present?
            instance_variable_set(:@internal_object, self.load)
          else
            instance_variable_set(:@internal_object, nil)
          end
        end
        instance_variable_get(:@internal_object)
      end
      
      def internal_object=(contents)
        if contents.is_a?(self.klass) || contents.nil?
          return @internal_object = contents 
        elsif contents.is_a?(self.class)
          return @internal_object = contents.internal_object
        # a Hash may be attributes and/or a service_uri
        elsif contents.is_a?(Hash) 
          contents = contents.symbolize_keys
          @remote_path = contents.delete(
            self.class.remote_path_element.to_sym
          )
          if contents.present?
            return @internal_object = self.klass.instantiate_record(contents)
          end
        else
          raise ArgumentError.new(
            "#{contents} must be a #{self.klass}, a #{self.class} or a Hash"
          )
        end
      end
      
      def ==(other)
        return false if self.class != other.class
        return false if other.internal_object.attributes != self.internal_object.attributes
        return true
      end

      def hash
        self.id.hash
      end

      def eql?(other)
        return self == other
      end


      def load(opts = {})
        data = self.klass.connection.get(self.build_load_path(opts))
        @loaded = true
        return nil if data.blank?
        return self.klass.instantiate_record(data)
      end

      
    end
    
  end
  
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
api_resource-0.5.1 lib/api_resource/associations/single_object_proxy.rb
api_resource-0.5.0 lib/api_resource/associations/single_object_proxy.rb