Sha256: a89d9254e8996a1faa49544317e3f80d5420cffdc0547aeb7f572e6f827e24ba

Contents?: true

Size: 1.11 KB

Versions: 31

Compression:

Stored size: 1.11 KB

Contents

# frozen_string_literal: true
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

31 entries across 31 versions & 1 rubygems

Version Path
active_mocker-2.4.0.pre1 lib/active_mocker/mock/records.rb
active_mocker-2.3.3 lib/active_mocker/mock/records.rb
active_mocker-2.3.2 lib/active_mocker/mock/records.rb
active_mocker-2.3.1 lib/active_mocker/mock/records.rb
active_mocker-2.3.0 lib/active_mocker/mock/records.rb
active_mocker-2.2.5 lib/active_mocker/mock/records.rb
active_mocker-2.2.4 lib/active_mocker/mock/records.rb
active_mocker-2.2.3 lib/active_mocker/mock/records.rb
active_mocker-2.2.2 lib/active_mocker/mock/records.rb
active_mocker-2.2.1 lib/active_mocker/mock/records.rb
active_mocker-2.2.0 lib/active_mocker/mock/records.rb