/
post.rb
executable file
·101 lines (81 loc) · 2.33 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
91
92
93
94
95
96
97
98
99
100
101
class Post < ActiveRecord::Base
# For distance_of_time_in_words
include ActionView::Helpers::DateHelper
belongs_to :user
belongs_to :ip
belongs_to :topic
belongs_to :edited_by, :class_name => "User"
has_many :edits, :order => "created_at DESC", :dependent => :destroy
has_many :moderations, :as => :moderated_object, :dependent => :destroy
has_many :reports, :as => :reportable, :dependent => :destroy
has_many :reporters, :through => :reports, :source => :user
validates_length_of :text, :minimum => 4
validates_presence_of :text
define_index do
indexes text
set_property :delta => true
end
delegate :subject, :to => :topic
attr_protected :forum_id, :user_id
after_create :log_ip
after_create :update_forum
before_create :stop_spam
after_create :find_latest_post
after_destroy :find_latest_post
before_create :increment_counter
before_destroy :decrement_counter
def increment_counter
forum.increment!(:posts_count)
end
def decrement_counter
forum.decrement!(:posts_count)
end
def stop_spam
if (!user.posts.last.nil? && user.posts.last.created_at > Time.now - TIME_BETWEEN_POSTS) && !user.can?(:ignore_flood_limit)
errors.add_to_base("You can only post once every #{distance_of_time_in_words(Time.now, Time.now - TIME_BETWEEN_POSTS)}") and return false
end
end
def log_ip
IpUser.create(:user => user, :ip => ip)
end
def update_forum
forum.last_post = self
Post.update_latest_post(self)
end
def self.update_latest_post(post)
post.forum.last_post = post
if post.forum.sub?
for ancestor in post.forum.ancestors
ancestor.last_post = post
ancestor.last_post_forum = post.forum
ancestor.save
end
end
post.forum.last_post = post
post.forum.last_post_forum = nil
post.forum.increment(:posts_count)
post.forum.save
end
def find_latest_post
last = forum.posts.last
if !last.nil?
last = Post.update_latest_post(last)
else
forum.last_post = nil
forum.last_post_forum = nil
forum.save
end
end
def editor
edits.last.user
end
def belongs_to?(other_user)
user == other_user
end
def forum
topic.forum
end
def page_for(user)
(topic.posts.count.to_f / (user.per_page || PER_PAGE)).ceil
end
end