Method: MovingCount.totals

Defined in:
lib/counter/moving_count.rb

.totals(opts = {}) ⇒ Object

Returns totals grouped by category across entire history. Optional filters can be used to filter totals:

* <tt>:limit</tt> limits results to top <em>n</em>
* <tt>:window</tt> limits totaled to samples to those in the past <em>n</em> seconds (can of course specify as 1.hour with ActiveSupport)
* <tt>:category_like</tt> run a LIKE match against categories before totaling, useful for limiting scope of totals.  '%' wildcards are allowed.


115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/counter/moving_count.rb', line 115

def self.totals opts={}
  latest_sample = self.maximum(:sample_time)
  return [] if latest_sample.nil? # don't try to run counts against empty db
  
  q  = "SELECT category, SUM(count) AS cnt FROM #{self.table_name}"
  
  where = []
  where << self.sanitize_sql(['category LIKE ?', opts[:category_like]])                       if opts[:category_like]
  where << self.sanitize_sql(['sample_time > ?', latest_sample - opts[:window]]) if opts[:window]
  
  q += " WHERE #{where.join(' AND ')}" unless where.empty?
  
  q += ' GROUP BY category'
  q += ' ORDER BY cnt DESC'
  q += " LIMIT #{opts[:limit]}" if opts[:limit]
  
  values = self.connection.select_rows(q)
  values.map { |v| v[1] = v[1].to_i }
  
  return values
end