Sha256: c77f2acb560a25c019dc2b3d924dc45450f7ac4dad6efdfe207b1d9cbc7c4b60

Contents?: true

Size: 1.18 KB

Versions: 5

Compression:

Stored size: 1.18 KB

Contents

module ActiveRecordFake

  def self.included(base)
    base.instance_variable_set(:@items, [])
    base.instance_variable_set(:@next_id, 1)    
    base.extend(ClassMethods)
  end


  attr_accessor :id

  def initialize options={}
    @id = options.fetch(:id) { self.class.get_next_id }
    set_attribute_values_from_options options.reject{|key, value| key == :id }
    self.class.add self
  end

  def delete!
    self.class.remove(self)
  end

  def update options={}
    set_attribute_values_from_options options
  end

  def attributes
    Hash[instance_variables.map { |name| [name, instance_variable_get(name)] } ]
  end

  module ClassMethods
    def create *args
      new *args
    end
    
    def delete_all
      @items.clear
      reset_id
      true
    end

    def all
      @items.dup
    end
    
    
    def add instance
      @items << instance
    end

    def remove instance
      @items.delete(instance)
    end

    def get_next_id
      id = @next_id
      @next_id += 1
      id
    end

    def reset_id
      @next_id = 1
    end
  end

  private

    def set_attribute_values_from_options options
      options.each{|attr, value| self.send("#{attr}=".to_sym, value) }
    end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
clockwork-2.0.4 test/database_events/support/active_record_fake.rb
clockwork-2.0.3 test/database_events/support/active_record_fake.rb
clockwork-2.0.2 test/database_events/support/active_record_fake.rb
clockwork-2.0.1 test/database_events/support/active_record_fake.rb
clockwork-2.0.0 test/database_events/support/active_record_fake.rb