Module: Juixe::Acts::Commentable::ClassMethods

Includes:
HelperMethods
Defined in:
lib/commentable_methods.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_commentable(*args) ⇒ Object



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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/commentable_methods.rb', line 67

def acts_as_commentable(*args)
  options = args.to_a.flatten.compact.partition{ |opt| opt.kind_of? Hash }
  comment_roles = 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.comment_types = (comment_roles.blank? ? [:comments] : comment_roles)

  if !comment_roles.blank?
    comment_roles.each do |role|
      define_role_based_inflection(role)
      accepts_nested_attributes_for "#{role.to_s}_comments".to_sym, allow_destroy: true, reject_if: proc { |attributes| attributes['comment'].blank? }
    end
    if RUBY_VERSION.first >= '3'
      has_many :all_comments, **{ :as => :commentable, :dependent => :destroy, class_name: 'Comment' }.merge(join_options)
    else
      has_many :all_comments, { :as => :commentable, :dependent => :destroy, class_name: 'Comment' }.merge(join_options)
    end
  else
    if RUBY_VERSION.first >= '3'
      has_many :comments, **{:as => :commentable, :dependent => :destroy}.merge(join_options)
    else
      has_many :comments, {:as => :commentable, :dependent => :destroy}.merge(join_options)
    end
    accepts_nested_attributes_for :comments, allow_destroy: true, reject_if: proc { |attributes| attributes['comment'].blank? }
  end

  comment_types.each do |role|
    method_name = (role == :comments ? "comments" : "#{role.to_s}_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.to_s}")
      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.to_s}"]).order("created_at DESC")
      end

      def #{method_name}_ordered_by_submitted
        Comment.find_comments_for_commentable(self.class.name, id, "#{role.to_s}").order("created_at")
      end

      def add_#{method_name.singularize}(comment)
        comment.role = "#{role.to_s}"
        #{method_name} << comment
      end
    }
  end
end