This library makes it easy to implement a Visualization data source so that you can easily chart or visualize your data from ActiveRecord models or from in-memory arrays. The library implements the Google Visualization API wire protocol.
It also allows you to render the visualizations in a view template in a very simple but powerful way.
This library is built on top of rgviz.
gem install rgviz-rails
In your Gemfile
gem 'rgviz' gem 'rgviz-rails', :require => 'rgviz_rails'
In your environment.rb
config.gem "rgviz" config.gem "rgviz-rails", :lib => 'rgviz_rails'
To make a method in your controller be a visualization API endpoint:
class VizController < ApplicationController def person # Person is an ActiveRecord::Base class render :rgviz => Person end end
So for example if Person has name and age, pointing your browser to:
http://localhost:3000/viz/person?select name where age > 20 limit 5
To enable the extensions defined by rgviz you need to specify it in the render method:
render :rgviz => Person, :extensions => true
If you want to filter, order by or group by columns that are in a model's association you can use underscores. This is better understood with an example:
class Person < ActiveRecord::Base belongs_to :city end class City < ActiveRecord::Base belongs_to :country end class Country < ActiveRecord::Base end
To select the name of the city each person belongs to:
To select the name of the country of the city each person belongs to:
A slightly more complex example:
select avg(age) where city_country_name = 'Argentina' group by city_name
The library will make it in just one query, writing all the SQL joins for you.
Sometimes you want to limit your results the query will work with. You can do it like this:
render :rgviz => Person, :conditions => ['age > ?', 20]
render :rgviz => Person, :conditions => 'age > 20'
If you need to tweak a result before returning it, just include a block:
render :rgviz => Person do |table| # Modify the Rgviz::Table object end
You can invoke the rgviz method in your views. Read more about this.
You can always do it the old way.
You can also apply a query over an array of arrays that contains your “records” to be queried.
types = [[:id, :number], [:name, :string], [:age, :number]] records = [ [1, 'John', 23], [2, 'Pete', 36] ] executor = Rgviz::MemoryExecutor.new records, types render :rgviz => executor
This is very useful if you need to present visualizations against data coming from a CSV file.
The format clause works, but formatting is as in ruby (like “%.2f” for numbers, “foo %s bar” for strings, and “%Y-%m-%d” for dates, as specified by Time#strftime)
Only supports MySQL, PostgreSQL and SQLite adapters
These scalar functions are not supported for SQLite: millisecond, quarter
These scalar functions are not supported for MySQL: millisecond
The function toDate doesn't accept a number as its argument
The tsv output format is not supported