Sha256: 7a2183143e3add0fb2c918ee700648f3052c28f4a68567cc930dc5e51100cbee

Contents?: true

Size: 958 Bytes

Versions: 23

Compression:

Stored size: 958 Bytes

Contents

class MockRecord
  IDS = Hash.new { |h, k| h[k] = 0 }
  QUERY_COUNTS = Hash.new { |h, k| h[k] = 0 }
  INSTANCES = Hash.new { |h, k| h[k] = {} }

  attr_reader :id

  class <<self
    def reset!
      IDS[name.to_sym] = 0
      INSTANCES[name.to_sym] = {}
    end
  end

  def initialize(attrs = {})
    attrs.each_pair do |name, value|
      send(:"#{name}=", value)
    end
    @id = IDS[self.class.name.to_sym] += 1
    INSTANCES[self.class.name.to_sym][@id] = self
  end

  def self.inherited(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def get(id)
      QUERY_COUNTS[self.name.to_sym] += 1
      get_instance(id)
    end

    def get_all(ids)
      QUERY_COUNTS[self.name.to_sym] += 1
      ids.map { |id| get_instance(id) }.sort_by { |instance| instance.id }
    end

    def query_count
      QUERY_COUNTS[self.name.to_sym]
    end

    private

    def get_instance(id)
      INSTANCES[self.name.to_sym][id]
    end
  end
end

Version data entries

23 entries across 23 versions & 7 rubygems

Version Path
sunspot-0.10.0 spec/mocks/mock_record.rb
sunspot-0.9.8 spec/mocks/mock_record.rb
sunspot-0.9.7 spec/mocks/mock_record.rb