Using Highcharts in Ruby on Rails in Headless Mode

19 Feb 2015

Using Highcharts is straightforward enough using the ruby on rails gem as you can see on my web site http://www.propertytrackerni.co.uk thanks to the gem lazy_high_charts. However what do we need to do is to use these graphing tool in a scheduled email ?

The answer is that we need a scheduled job to call this browser based javascript graphing tool from the command line and we need this scheduled routine to first export the graphing info out to json.

To export this data in json take a look at the below code

volcnty = @graphservice.fndavgprcmthyr
cats = {:categories => volcnty.category}
icnt = 0
vdata = Array.new
volcnty.series.each do |volitm|
vdata << Hash(:name => volcnty.arrseries[icnt], :data => volitm)
icnt+=1
end
types = {:type => "line"}
yax = {:title => {:text => "Average Asking Price"}}
graphdat = {:chart => types,:title => "Average Asking Price over the year",:xAxis => cats,:yAxis => yax, :series => vdata}
File.open("#{Rails.root}/highchart/exporting-server/phantomjs/#{@currtrans.id}__avgyr.json", "w") { |f| f.write(graphdat.to_json) }

The routine @graphservice.fndavgprcmthyr calls our postgres view and returns the result as an object which contains the results of our query, To write the data in a format highchart will understand we need to use the json put in the below format

graphdat = {:chart => types,:title => "Average Asking Price over the year",:xAxis => cats,:yAxis => yax, :series => vdata}

A shell script needs to be called to call highcharts and convery the json into a png which can be loaded into our email

system("sh #{Rails.root}/highchart/exporting-server/phantomjs/phantomjs.sh #{Rails.root} #{@currtrans.id}__volyr_#{searchp.id}.json volyr_#{searchp.id}_#{@currtrans.id}.png")

This shell script contains the below code

cd $1/highchart/exporting-server/phantomjs
phantomjs highcharts-convert.js -infile $2 -outfile $1/public/export/$3 -scale 2.5 -width 300 -constr Chart

The highcharts-convert.js and the associated files can be found on the highcharts web site

Published on 19 Feb 2015 Find me on Twitter!