Git Product home page Git Product logo

rgviz-rails's Introduction

rgviz-rails

Build Status

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.

Installation

gem install rgviz-rails

Rails 3

In your gemfile

gem 'rgviz'
gem 'rgviz-rails', :require => 'rgviz_rails'

Rails 2.x

In your environment.rb

config.gem "rgviz"
config.gem "rgviz-rails", :require => 'rgviz_rails'

Usage

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 <ttPperson has name and age, pointing your browser to:

http://localhost:3000/viz/person?tq=select name where age > 20 limit 5

would render the necessary javascript code that implements the google visualization api wire protocol.

Associations

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:

select city_name

To select the name of the country of the city each person belongs to:

select city_country_name

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.

Extra conditions

Sometimes you want to limit your results the query will work with. You can do it like this:

render :rgviz => Person, :conditions => ['age > ?', 20]

or also:

render :rgviz => Person, :conditions => 'age > 20'

or (Rails 3 only):

render :rgviz => Person.where('age > ?', 20)

Preprocessing

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

Showing a visualization in a view

You can invoke the rgviz method in your views. read more about this.

You can always do it the old way.

Executing queries over in-memory arrays

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.

Virtual columns

GQL is nice but it's not very powerful (except for the cute pivot clause).

If you need to select columns using complex SQL, you might be able to do it with virtual columns.

For example, in your controller you put:

render :rgviz => Person, :virtual_columns => {
    'age_range' => {
        :sql => "case when age < 20 then 'young' else 'old' end",
        :type => :string
    }
}

Then in a query you can do:

select age_range ...

Note that the keys of the virtual_columns hash must be strings. The value can be a hash with :sql and :type key-value pairs (since GQL needs the type of every column), or can be just a string if you want the column to be replaced by another GQL expression. For example:

render :rgviz => Person, :virtual_columns => {
    'age_plus_two' => 'age + 2'
}

Current limitations

  • 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

Contributors

rgviz-rails's People

Contributors

amolk avatar asterite avatar bradseefeld avatar juanboca avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

rgviz-rails's Issues

Always include corecharts when loading "Kind"

I am seeing slightly different behavior between these two:

// Shown in Google's examples for Pie Charts
google.load("visualization", "1", {packages:["corechart"]});

and

// What Rgviz loads
google.load("visualization", "1", {packages:["piechart"]});

Some differences when only piechart is loaded:

  • Border does not appear when hovering
  • Text inside slices does not appear
  • Tooltip does not appear on hover (only on click)

I think the easy fix is just always load "corechart" and then optionally other packages.

Missing template exception when using rails 3 edge

When using:

render :rgviz => Model

I get the following exception about a missing template:

ActionView::MissingTemplate (Missing template foo/bar/baz with {:handlers=>[:erb, :rjs, :builder], :formats=>[:html, :text, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json], :locale=>[:en, :en]} in view paths ....

Rendered /path/.bundler/ruby/1.9.1/rails-32a2bf8d4e17/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.erb within rescues/layout (0.5ms)

I am able to get output through the following code:

query = params[:tq]
 executor = Rgviz::Executor.new(Foo::Yo, query)
 table = executor.execute

 tqx = params[:tqx] || ''
 tqx = Rgviz::Tqx.parse(tqx)

 case tqx['out']
 when 'json'
   data = Rgviz::JsRenderer.render(table, tqx)
 when 'html'
   data = Rgviz::HtmlRenderer.render(table)
 when 'csv'
   # TODO: Force download
   data = Rgviz::CsvRenderer.render(table)
 end

 render :text => data

JS magic names are ignored inside hashes

When creating a visualization using the rgviz view helper, js magic names are not converted to the function invocation if they are within a hash. For example:

rgviz :options => {:width => "js_calculateWidth"}

Works and is properly translated as {width: calculateWidth()}

However, the following code:

rgviz :options => {:chartArea => {:width => "js_calculateChartAreaWidth"}}

Is not parsed and translated as {chartArea: {width: "js_calculateAreaWidth"}}

Passing in an empty array of additional conditions results in a bad sql query

I have something like this in my controller:

def index
  if current_user.admin?
    conditions = []
  else
    conditions = ["user_id = ?", current_user.id]
  end

  render :rgviz => Model, :conditions => conditions
end

If the incoming query has its own WHERE clause and conditions is an empty array, the resulting SQL query ends up with an extra AND.

For example, incoming client query is: SELECT * WHERE a = b. If conditions is an empty array, the resulting SQL is SELECT * FROM models WHERE a = b AND Passing in nil instead of an empty array provides the correct functionality.

Easy enough to work around but was unexpected.

Associations that include underscores are not automatically found

The method OrderVisitor.find_rails_col fails to find an association if the association has an underscore. For example:

class Foo < ActiveRecord::Base
  has_many :foo_bar
end

class FooBar < ActiveRecord::Base
  belongs_to :foo
end

A query: SELECT * WHERE foo_bar_id = 10; would fail. It assumes the association is named 'foo' and the column is 'bar_id'.

Executing queries over in-memory arrays example not working

I have a project that is successfully using "render :rgviz => Person". However, when I try to execute the example under "Executing queries over in-memory arrays" I get "google.visualization.Query.setResponse({reqId:'1',status:'error',version:'0.6',errors:[{reason:'invalid_query', message:'wrong number of arguments (2 for 1)}]});" My query is "select name".

This is caused because the execute method in rgviz memory_executor.rb (line 15) was changed to not allow the options parameter to be passed in.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.