Module: Mongoid::Utils::Commentable::ClassMethods

Defined in:
lib/mongoid/utils/commentable.rb

Instance Method Summary collapse

Instance Method Details

#discussable_by(param, options = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/mongoid/utils/commentable.rb', line 14

def discussable_by(param, options = {})
  range = case param
    when 'day'; Time.now.at_beginning_of_day..Time.now
    when 'week'; Time.now.at_beginning_of_week..Time.now
    when 'month'; Time.now.at_beginning_of_month..Time.now
    when 'year'; Time.now.at_beginning_of_year..Time.now
  end

  filter = []
  filter << { :$match => {commentable_type: self.name, _id: {:$gte => BSON::ObjectId.from_time(range.first), :$lte => BSON::ObjectId.from_time(range.last)} } }
  filter << { :$group => {_id: '$commentable_id', count: {:$sum => 1}} }
    #      filter << { :$sort => {count: -1} }
  filter << { :$limit => options[:limit].to_i } if options.key?(:limit)

  ids = Comment.collection.aggregate(filter).collect { |raw| raw[:_id] }

  where(:id.in => ids)
end