/
post.rb
90 lines (71 loc) · 1.18 KB
/
post.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
require 'active_model'
class Post
extend ActiveModel::Naming
include ActiveModel::Validations
class << self
def posts
POSTS
end
private :posts
def all
posts.compact
end
def create(attrs = {})
post = new(attrs)
post.save
post
end
def persist(post)
id = posts.length
posts << post
id
end
def unpersist(post)
posts[post.id] = nil
end
def find(id)
posts[id.to_i] or raise "not found"
end
def count
posts.compact.length
end
end
attr_reader :id
attr_accessor :title, :body
def initialize(attrs = {})
self.attributes = attrs
end
def attributes=(attrs)
return unless attrs
attrs.each { |k, v| send("#{k}=", v) }
end
def attributes
{ 'title' => title, 'body' => body }
end
def to_model
self
end
def to_param
id.to_s
end
def to_key
[id] if id
end
def persisted?
!id.nil?
end
def save
unless persisted?
@id = self.class.persist(self)
end
true
end
def update_attributes(attrs)
self.attributes = attrs
save
end
def destroy
self.class.unpersist(self)
true
end
end