Sha256: 183c74bdfe8b84edf9dadad7e36047f006a22503feab29796ab536568d677d84

Contents?: true

Size: 1.08 KB

Versions: 7

Compression:

Stored size: 1.08 KB

Contents

module ActiveMocker
  class Records

    extend Forwardable
    def_delegators :records, :<<, :count, :length, :to_a

    attr_reader :records
    private :records

    def initialize(records = [])
      @records = records
    end

    def insert(record)
      records << validate_id((record.id ||= next_id), record)
    end

    def delete(record)
      raise RecordNotFound, 'Record has not been created.' unless records.delete(record)
    end

    def exists?(record)
      records.include?(record)
    end

    def new_record?(record)
      !exists?(record)
    end

    def persisted?(id)
      ids.include?(id)
    end

    def reset
      records.clear
    end

    private

    def ids
      records.map(&:id)
    end

    def next_id
      max_record.succ
    rescue NoMethodError
      1
    end

    def max_record
      ids.max
    end

    def validate_id(id, record)
      record.id = id.to_i
      validate_unique_id(id, record)
    end

    def validate_unique_id(id, record)
      raise IdError, "Duplicate ID found for record #{record.inspect}" if persisted?(id)
      record
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
active_mocker-2.1.3 lib/active_mocker/mock/records.rb
active_mocker-2.1.2 lib/active_mocker/mock/records.rb
active_mocker-2.1.1 lib/active_mocker/mock/records.rb
active_mocker-2.1.0 lib/active_mocker/mock/records.rb
active_mocker-2.0.0 lib/active_mocker/mock/records.rb
active_mocker-2.0.0.rc1 lib/active_mocker/mock/records.rb
active_mocker-2.0.0.pre1 lib/active_mocker/mock/records.rb