@@ -15,9 +15,18 @@ def count
15
15
alias_method :size , :count
16
16
alias_method :length , :count
17
17
18
+ def find ( id )
19
+ id = id . to_i
20
+ all . find { |record | record . id == id } || raise
21
+ end
22
+
23
+ def last
24
+ all . last
25
+ end
26
+
18
27
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
21
30
record
22
31
end
23
32
@@ -38,16 +47,49 @@ class Model
38
47
include ::ActiveModel ::Validations
39
48
40
49
def initialize ( attributes = { } )
41
- attributes . each do |name , value |
42
- send ( "#{ name } =" , value )
43
- end
50
+ assign_attributes ( attributes )
44
51
end
45
52
end
46
53
47
54
attr_accessor :id , :persisted
48
55
49
56
alias_method :persisted? , :persisted
50
57
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
+ return false unless other . is_a? ( self . class )
86
+ id == other . id
87
+ end
88
+
89
+ def persisted?
90
+ !id . nil?
91
+ end
92
+
51
93
def new_record?
52
94
!persisted?
53
95
end
0 commit comments