Embedding Google Analytics Charts Into A Rails App

It is a straight forward operation to be honest, it took much reading and much less code to get it done, hope this saves some other folks some time.

This is how it’s gonna look like in the end

highcharts

Trying to connect to communicate to the google analytics API is a bit tricky and takes some time to get it right, you have to use HTTP headers and what-not, I went through this route first thinking that there weren’t any Ruby gems to do, guess I was mistaken.

The gem that suited my needs is garb, pretty decent but you would still have to read the wiki to understand how it works.

First establish a new sessions and bind to the profile that you want

Garb::Session.login('email@example.com', 'password', :account_type => 'GOOGLE_OR_HOSTED')
profile = Garb::Profile.first('UA-XXXXXXXX-X')

I have also declared a class so I can get the reports I want filtered by URL

class ViewsVisits
    extend Garb::Resource
    metrics :visits, :page_views
    dimensions :date
    @@path = ''
    def ViewsVisits.path
      @@path
    end
    def ViewsVisits.path=(value)
      @@path = value
    end

    filters do
      matches(:page_path, "#{@@path}")
    end
  end

I then iterate over the entities that I want to get the stats for

    @entities = []
    @entities.concat(Restaurant.published)
    @entities.each do |e|
      ViewsVisits.path = "/" + e.class.to_s.pluralize.underscore + "/" + e.id.to_s
      report = ViewsVisits.results(profile, :start_date => (Date.today - 31),:end_date => (Date.today - 1) )
      #save the result in the DB for latter processing
    end

All good so far, remember to serialize the column into which you plan to save report.

Now lets head into generating a nice little chart for this data, I decided to go with Highcharts, first lets parse the data into array where @pvarray is for page views and @varray is for visits.

      @pvarray = []
      @varray = []
      @entity.info.views_stats.each do |r|
        @pvarray << r.pageviews
        @varray << r.visits
      end

and the following Javascript should render this data in a lovely fashion

<script type="text/javascript">

  	var chart;
  	$j(document).ready(function() {
  		chart = new Highcharts.Chart({
  			chart: {
  				renderTo: 'container',
  				defaultSeriesType: 'area'
  			},
  			title: {
  				text: 'Views and Visits over the last 30 days'
  			},
  			xAxis: {
  			  type: "datetime"
  			},
  			yAxis: {
  			  type: "linear",
  			  title: "pew",
  			  min: 0,
  				labels: {
  				  enabled: false
  				}
  			},
  			tooltip: {
  				formatter: function() {
  					return this.series.name +':<b>'+ Highcharts.numberFormat(this.y, 0, null, ' ')+'</b>';
  				}
  			},
  			plotOptions: {
  				series: {
  					pointStart: Date.UTC(<%=  (Date.today - 31).strftime("%Y").to_s %>, <%=  (Date.today - 31).strftime("%m").to_i - 1 %>, <%=  (Date.today - 31).strftime("%d").to_s %>),
  					pointInterval: 24 * 3600 * 1000, // one day
  				}
  			},
  			series: [{
  				name: 'Views',
  				data: [<%= @pvarray.join(",").to_s %>]
  			}, {
  				name: 'Visits',
  				data: [<%= @varray.join(",").to_s %>]
  			}]
  		});

  	});

  </script>

Leave a comment