-
Notifications
You must be signed in to change notification settings - Fork 166
/
Copy pathacts_as_commentable_with_threading.rb
66 lines (57 loc) · 2.08 KB
/
acts_as_commentable_with_threading.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
require 'active_record'
require 'awesome_nested_set'
ActiveRecord::Base.class_eval do
include CollectiveIdea::Acts::NestedSet
end
#
unless ActiveRecord::Base.respond_to?(:acts_as_nested_set)
ActiveRecord::Base.send(:include, CollectiveIdea::Acts::NestedSet::Base)
end
# ActsAsCommentableWithThreading
module Acts #:nodoc:
module CommentableWithThreading #:nodoc:
extend ActiveSupport::Concern
module ClassMethods
def acts_as_commentable
has_many :comment_threads, class_name: 'Comment', as: :commentable
before_destroy { |record| record.root_comments.destroy_all }
include Acts::CommentableWithThreading::LocalInstanceMethods
extend Acts::CommentableWithThreading::SingletonMethods
end
end
# This module contains class methods
module SingletonMethods
# Helper method to lookup for comments for a given object.
# This method is equivalent to obj.comments.
def find_comments_for(obj)
Comment.where(commentable_id: obj.id,
commentable_type: obj.class.base_class.name)
.order('created_at DESC')
end
# Helper class method to lookup comments for
# the mixin commentable type written by a given user.
# This method is NOT equivalent to Comment.find_comments_for_user
def find_comments_by_user(user)
commentable = base_class.name.to_s
Comment.where(user_id: user.id, commentable_type: commentable)
.order('created_at DESC')
end
end
module LocalInstanceMethods
# Helper method to display only root threads, no children/replies
def root_comments
comment_threads.where(parent_id: nil)
end
# Helper method to sort comments by date
def comments_ordered_by_submitted
Comment.where(commentable_id: id, commentable_type: self.class.name)
.order('created_at DESC')
end
# Helper method that defaults the submitted time.
def add_comment(comment)
comments << comment
end
end
end
end
ActiveRecord::Base.send(:include, Acts::CommentableWithThreading)