module Mongoid::Utils::Commentable::ClassMethods

Public Instance Methods

discussable_by(param, options = {}) click to toggle source
# 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