A simple way to grab recent activity on a given model grouped by hour, day, week or month (time series). Supports “padding” for intervals without activity.
Add gem to Gemfile…
gem 'has-activity'
Add the activity functionality to a model…
# app/models/user.rb has_activity :on => :created_at
Query for activity…
# Calculate activity from 1 month ago, grouped by each day, for active users... User.where("active = 1").activity_since(1.month.ago, :by => :day) => [{ :offset => 31, :activity => 5, :timestamp => 2012-03-18 17:00:00 -0700 }, { :offset => 30, :activity => 12, :timestamp => 2012-03-17 17:00:00 -0700 }, ... ] # Other examples... # Calculate the new users per hour in the last day... User.activity_since(1.day.ago, :by => :hour) # Calculate the new users per week for January of 2012... User.activity_between(Date.parse("2012-01-01"), Date.parse("2012-01-31"), :by => :week)
Graph the data…
# Google charts sparkline... User.activity_since(1.day.ago, :by => :hour).to_activity_gchart => http://chart.apis.google.com/chart?chs=200x50&cht=ls&chco=0077CC&chm=B,DFEBFF,0,0,0&chd=t:17,252,105,80,25,99,333,39,98,17,252,105,80,25,99,333,39,98&chds=0,333&chf=bg,s,EFEFEF& # D3 charts... soon... # Or create your own... data = User.activity_since(Date.today.beginning_of_month, :by => :day) data.collect { |d| [d[:activity], d[:timestamp].strftime("%d/%m (%A)")] } => [[5, "1/1 (Tuesday)"], [12, "1/2 (Wednesday)"], [33, "1/3 (Thursday)"], ...]
Copyright © 2012 Cary Dunn. See LICENSE.txt for further details.