Sha256: 80b99e41fcacec6bc9d348986be900c4f7e2c5c4c2c371b12c369a58963ae02e

Contents?: true

Size: 1.43 KB

Versions: 1

Compression:

Stored size: 1.43 KB

Contents

module MotionResource
  class Base
    include MotionSupport::DescendantsTracker
    
    class_attribute :primary_key
    self.primary_key = :id
    
    attr_accessor :id
    
    def initialize(params = {})
      @new_record = true
      update_attributes(params)
    end
    
    def new_record?
      @new_record
    end
    
    class << self
      def instantiate(json)
        if json.is_a?(Hash)
          json = json.symbolize_keys
        else
          json = { primary_key => json.to_i }
        end
        
        raise ArgumentError, "No :#{primary_key} parameter given for #{self.name}.instantiate" unless json[primary_key]
        
        klass = if json[:type]
          begin
            Object.const_get(json[:type].to_s)
          rescue NameError
            self
          end
        else
          self
        end
        
        if result = klass.recall(json[primary_key])
          result.update_attributes(json)
        else
          result = klass.new(json)
          klass.remember(result.send(result.primary_key), result)
        end
        result.send(:instance_variable_set, "@new_record", false)
        result
      end
      
      def json_root
        self.name.underscore.pluralize
      end

      def identity_map
        @identity_map ||= {}
      end
      
      def remember(id, value)
        identity_map[id] = value
      end
      
      def recall(id)
        identity_map[id]
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
motion-resource-0.1.4 lib/motion-resource/base.rb