Using GRUFF with Ruby on Rails

Gruff is a RoR plugin to generate On-The-Fly graphs within the Web Application. Developed by Geoffrey Grosenbach you can find the Plugin Home Page at http://nubyonrails.com/pages/gruff

The API documentation can be found at http://gruff.rubyforge.org/

Example Graphs

Installation
Simple type in the following command to install Gruff


sudo gem install gruff

To use it in a Rails project you can also unpack the gem into the vendor/plugins directory and add the following line to environment.rb located in the config directory

require 'gruff'

 

Sample Basic Graph

g = Gruff::Line.new #Define a New Graph
g.title = "My Graph" #Title for the Graph

g.data("Apples", [1, 2, 3, 4, 4, 3]) #Graph Data
g.data("Oranges", [4, 8, 7, 9, 8, 9])
g.data("Watermelon", [2, 3, 1, 5, 6, 8])
g.data("Peaches", [9, 9, 10, 8, 7, 9])

g.labels = {0 => '2003', 2 => '2004', 4 => '2005'} #Labels for Each of the Graph

g.write('my_fruity_graph.png')

The about graph will write a graph to the file to my_fruity_graph.png. In case you want to generate graphs dynamically without writing to a file you can do so through the following

send_data(g.to_blob, :disposition => 'inline', :type => 'image/png', :filename => "arbitaryfilename.png")

The above line simlple gets the graph data and displays it with an image header. I have used g.to_blob to repeatedly updates graphs on Reports.

 

SQL Query to Retrieve records grouped by dates

I have used the following query to retrieve all the graph data ordered by Date. After retrieving the data to an array I wrote a function which fills in empty data for the days that dont have data. The query does an excellent job of retrieving a lot of data within a given date range. I used the query for a Banner Management Tool to get Clicks and Views Statistics for a period of time.

SELECT COUNT( * ) AS data, DATE_FORMAT( created_at, '%Y-%m-%d' ) AS
day FROM `adlogs`
WHERE CLICK = " + clicks.to_s +
" AND BANNER_ID = " + id.to_s +
" AND created_at > '" + qstart.to_s + "'
AND created_at < '" + qend.to_s + "'
GROUP BY DATE_FORMAT( created_at, '%Y %m %d' )
ORDER BY DATE_FORMAT( created_at, '%Y %m %d' ) ASC