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
|
# File 'lib/commentable_methods.rb', line 33
def (*args)
return if method_defined?(:comment_types)
options = args.to_a.flatten.compact.partition { |opt| opt.is_a? Hash }
= options.last.blank? ? nil : options.last.flatten.compact.map(&:to_sym)
join_options = options.first.blank? ? [{}] : options.first
throw 'Only one set of options can be supplied for the join' if join_options.length > 1
join_options = join_options.first
class_attribute :comment_types
self. = (.blank? ? [:comments] : )
if .blank?
has_many :comments, as: :commentable, dependent: :destroy, **join_options
else
.each do |role|
define_role_based_inflection(role)
end
has_many :all_comments, as: :commentable, dependent: :destroy, class_name: 'Comment', **join_options
end
.each do |role|
method_name = (role == :comments ? 'comments' : "#{role}_comments").to_s
class_eval %{
def self.find_#{method_name}_for(obj)
commentable = self.base_class.name
Comment.find_comments_for_commentable(commentable, obj.id, "#{role}")
end
def self.find_#{method_name}_by_user(user)
commentable = self.base_class.name
Comment.where([
"user_id = ? and commentable_type = ? and role = ?", user.id, commentable, "#{role}"
]).order("created_at DESC")
end
def #{method_name}_ordered_by_submitted
Comment.find_comments_for_commentable(self.class.name, id, "#{role}").order("created_at")
end
def add_#{method_name.singularize}(comment)
comment.role = "#{role}"
#{method_name} << comment
end
}, __FILE__, __LINE__ - 21
end
end
|