Sha256: 76e42ef52a8633a1461bce23bfa56b70a3a2a3f7bb95419b1cf242f812b82a3c

Contents?: true

Size: 1.06 KB

Versions: 1

Compression:

Stored size: 1.06 KB

Contents

module MotionResource
  class Base
    attr_accessor :id
    
    def initialize(params = {})
      @new_record = true
      update_attributes(params)
    end
    
    def new_record?
      @new_record
    end
    
    class << self
      def instantiate(json)
        raise ArgumentError, "No :id parameter given for #{self.name}.instantiate" unless json[:id]
        
        klass = if json[:type]
          begin
            Object.const_get(json[:type].to_s)
          rescue NameError
            self
          end
        else
          self
        end
        
        if result = klass.recall(json[:id])
          result.update_attributes(json)
        else
          result = klass.new(json)
          klass.remember(result.id, result)
        end
        result.send(:instance_variable_set, "@new_record", false)
        result
      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.0.1 lib/motion-resource/base.rb