Class: MemoryModel::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/memory_model/collection.rb

Defined Under Namespace

Classes: InvalidTypeError

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model = Class.new) ⇒ Collection

Returns a new instance of Collection.



12
13
14
15
16
# File 'lib/memory_model/collection.rb', line 12

def initialize(model=Class.new)
  @model   = model
  @records = []
  self.class.all << self
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object (private)



64
65
66
# File 'lib/memory_model/collection.rb', line 64

def method_missing(m, *args, &block)
  all.respond_to?(m) ? all.send(m, *args, &block) : super
end

Class Attribute Details

.allObject

Returns the value of attribute all.



7
8
9
# File 'lib/memory_model/collection.rb', line 7

def all
  @all
end

Instance Method Details

#allObject



18
19
20
# File 'lib/memory_model/collection.rb', line 18

def all
  unique.reject(&:deleted?)
end

#deletedObject



22
23
24
# File 'lib/memory_model/collection.rb', line 22

def deleted
  unique.select(&:deleted?)
end

#find(id, options = { }) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/memory_model/collection.rb', line 26

def find(id, options={ })
  version        = options[:version] || 0
  return_deleted = !!options[:deleted]
  record         = sorted.select { |r| r.id == id }[version]
  return nil unless record
  if !record.deleted? || (return_deleted && record.deleted?)
    record
  else
    raise MemoryModel::RecordNotFoundError
  end
end

#insert(record) ⇒ Object Also known as: <<

Raises:



38
39
40
41
42
43
44
# File 'lib/memory_model/collection.rb', line 38

def insert(record)
  raise InvalidTypeError unless record.is_a? @model
  record = record.dup
  record.freeze unless record.frozen?
  @records << record
  self
end

#inspectObject



48
49
50
# File 'lib/memory_model/collection.rb', line 48

def inspect
  self.all.inspect
end

#records(dup = true) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/memory_model/collection.rb', line 52

def records(dup = true)
  if dup
    @records.map do |record|
      record.deleted? ? record : record.dup
    end
  else
    @records
  end
end