Skip to content

Commit 4e3d2d9

Browse files
yujinakayamasebjacobs
authored andcommitted
Enhance InMemory::Model in the no AR example app
1 parent 2bbd831 commit 4e3d2d9

File tree

1 file changed

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

1 file changed

+48
-5
lines changed

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

Lines changed: 48 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,50 @@ 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+
alias_method :update_attributes, :update
64+
65+
def assign_attributes(attributes)
66+
attributes.each do |name, value|
67+
__send__("#{name}=", value)
68+
end
69+
end
70+
71+
def save(*)
72+
self.id = self.class.next_id
73+
self.class.all << self
74+
true
75+
end
76+
77+
def destroy
78+
self.class.all.delete(self)
79+
true
80+
end
81+
82+
def reload(*)
83+
self
84+
end
85+
86+
def ==(other)
87+
other.is_a?(self.class) && id == other.id
88+
end
89+
90+
def persisted?
91+
!id.nil?
92+
end
93+
5194
def new_record?
5295
!persisted?
5396
end

0 commit comments

Comments
 (0)