Class: Records

Inherits:
Object
  • Object
show all
Defined in:
lib/active_mock/records.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(records = []) ⇒ Records

Returns a new instance of Records.



5
6
7
# File 'lib/active_mock/records.rb', line 5

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

Instance Attribute Details

#recordsObject (readonly)

Returns the value of attribute records.



3
4
5
# File 'lib/active_mock/records.rb', line 3

def records
  @records
end

Instance Method Details

#<<(record) ⇒ Object



22
23
24
# File 'lib/active_mock/records.rb', line 22

def <<(record)
  records << record
end

#add_to_record_index(entry) ⇒ Object



36
37
38
# File 'lib/active_mock/records.rb', line 36

def add_to_record_index(entry)
  record_index.merge!(entry)
end

#clearObject



44
45
46
# File 'lib/active_mock/records.rb', line 44

def clear
  records.clear
end

#delete(record) ⇒ Object



16
17
18
19
20
# File 'lib/active_mock/records.rb', line 16

def delete(record)
  record_index.delete("#{record.id}")
  index = records.index(record)
  records.delete_at(index)
end

#exists?(record) ⇒ Boolean

Returns:

  • (Boolean)


67
68
69
70
71
# File 'lib/active_mock/records.rb', line 67

def exists?(record)
  if record.id.present?
    record_index[record.id.to_s].present?
  end
end

#insert(record) ⇒ Object



9
10
11
12
13
14
# File 'lib/active_mock/records.rb', line 9

def insert(record)
  record.attributes[:id] ||= next_id
  validate_unique_id(record)
  add_to_record_index({record.id.to_s => records.length})
  records << record
end

#lengthObject Also known as: count



26
27
28
# File 'lib/active_mock/records.rb', line 26

def length
  records.length
end

#new_record?(record) ⇒ Boolean

Returns:

  • (Boolean)


73
74
75
# File 'lib/active_mock/records.rb', line 73

def new_record?(record)
  !records.include?(record)
end

#next_idObject



57
58
59
# File 'lib/active_mock/records.rb', line 57

def next_id
  NextId.new(records).next
end

#persisted?(id) ⇒ Boolean

Returns:

  • (Boolean)


77
78
79
# File 'lib/active_mock/records.rb', line 77

def persisted?(id)
  records.map(&:id).include?(id)
end

#record_indexObject



32
33
34
# File 'lib/active_mock/records.rb', line 32

def record_index
  @record_index ||= {}
end

#reset_all_recordsObject



52
53
54
55
# File 'lib/active_mock/records.rb', line 52

def reset_all_records
  reset_record_index
  clear
end

#reset_record_indexObject



40
41
42
# File 'lib/active_mock/records.rb', line 40

def reset_record_index
  record_index.clear
end

#to_aObject



48
49
50
# File 'lib/active_mock/records.rb', line 48

def to_a
  records
end

#validate_unique_id(record) ⇒ Object



61
62
63
64
65
# File 'lib/active_mock/records.rb', line 61

def validate_unique_id(record)
  if record_index.has_key?(record.id.to_s)
    raise ActiveMock::IdError.new("Duplicate ID found for record #{record.attributes.inspect}")
  end
end