Skip to content

Commit 875923b

Browse files
committed
Enhance InMemory::Model in the no AR example app
1 parent 5bfa9ab commit 875923b

File tree

1 file changed

+46
-5
lines changed
  • example_app_generator/no_active_record/app/models/in_memory

1 file changed

+46
-5
lines changed

example_app_generator/no_active_record/app/models/in_memory/model.rb

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,18 @@ def count
1515
alias_method :size, :count
1616
alias_method :length, :count
1717

18+
def last
19+
all.last
20+
end
21+
22+
def find(id)
23+
id = id.to_i
24+
all.find { |record| record.id == id } || raise
25+
end
26+
1827
def create!(attributes = {})
19-
with_id = { :id => next_id, :persisted => true }
20-
all << record = new(with_id.merge(attributes))
28+
record = new(attributes)
29+
record.save
2130
record
2231
end
2332

@@ -38,16 +47,48 @@ class Model
3847
include ::ActiveModel::Validations
3948

4049
def initialize(attributes = {})
41-
attributes.each do |name, value|
42-
send("#{name}=", value)
43-
end
50+
assign_attributes(attributes)
4451
end
4552
end
4653

4754
attr_accessor :id, :persisted
4855

4956
alias_method :persisted?, :persisted
5057

58+
def update(attributes)
59+
assign_attributes(attributes)
60+
save
61+
end
62+
63+
def assign_attributes(attributes)
64+
attributes.each do |name, value|
65+
__send__("#{name}=", value)
66+
end
67+
end
68+
69+
def save(*)
70+
self.id = self.class.next_id
71+
self.class.all << self
72+
true
73+
end
74+
75+
def destroy
76+
self.class.all.delete(self)
77+
true
78+
end
79+
80+
def reload(*)
81+
self
82+
end
83+
84+
def ==(other)
85+
other.is_a?(self.class) && id == other.id
86+
end
87+
88+
def persisted?
89+
!id.nil?
90+
end
91+
5192
def new_record?
5293
!persisted?
5394
end

0 commit comments

Comments
 (0)