@@ -16,6 +16,8 @@ class CommentThread < ApplicationRecord
1616
1717 after_create :create_follower
1818
19+ before_save :bump_last_activity
20+
1921 # Gets threads appropriately scoped for a given user & post
2022 # @param user [User, nil] user to check
2123 # @para post [Post] post to check
@@ -51,9 +53,9 @@ def can_access?(user)
5153
5254 # Gets last activity date and time on the thread
5355 # @return [DateTime] last activity date and time
54- def last_activity_at
55- last_comment_activity_at = comments . map ( &:last_activity_at ) . max
56- [ created_at , locked_at , updated_at , last_comment_activity_at ] . compact . max
56+ def last_activity
57+ last_comment_activity = comments . map ( &:last_activity ) . compact . max
58+ [ created_at , updated_at , last_activity_at , last_comment_activity ] . compact . max
5759 end
5860
5961 # Gets a list of user IDs who should be pingable in the thread.
@@ -86,6 +88,40 @@ def maximum_title_length
8688 end
8789 end
8890
91+ # Registers a given user as a follower of the thread
92+ # @param user [User] user to register as a follower
93+ # @return [Boolean] status of the operation
94+ def add_follower ( user )
95+ if ThreadFollower . where ( comment_thread : self , user : user ) . any?
96+ bump_last_activity ( persist_changes : true )
97+ return true
98+ end
99+
100+ ThreadFollower . create ( comment_thread : self , user : user )
101+ end
102+
103+ # Directly bumps the thread's last activity date & time
104+ # @param persist_changes [Boolean] if set to +true+, will persist the changes
105+ def bump_last_activity ( persist_changes : false )
106+ self . last_activity_at = DateTime . now
107+
108+ if persist_changes
109+ save
110+ end
111+ end
112+
113+ # Removes a given user from the thread's followers
114+ # @param user [User] user to remove from followers
115+ # @return [Boolean] status of the operation
116+ def remove_follower ( user )
117+ if ThreadFollower . where ( comment_thread : self , user : user ) . none?
118+ bump_last_activity ( persist_changes : true )
119+ return true
120+ end
121+
122+ ThreadFollower . where ( comment_thread : self , user : user ) . destroy_all . any?
123+ end
124+
89125 private
90126
91127 # Comment author and post author are automatically followed to the thread. Question author is NOT
0 commit comments