Skip to content

Instantly share code, notes, and snippets.

@peponi
Created June 13, 2012 09:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peponi/2923081 to your computer and use it in GitHub Desktop.
Save peponi/2923081 to your computer and use it in GitHub Desktop.
use the HighCharts lib in Rails by using LazyHighCharts
# find the reference here -> http://www.highcharts.com/ref
# github.com/michelson/lazy_high_charts
require "lazy_high_charts"
class CreateGraph
def init()
mess = []
# -- save me the SUM() of Messages for every day in the last week
(0..6).each do |i|
mess[i] = Message.count(:all, :conditions => ["created_at between ? and ?", (i+1).days.ago, i.days.ago])
end
message_graph = LazyHighCharts::HighChart.new('graph') do |f|
f.options[:chart][:defaultSeriesType] = "area"
f.title( :text => "Messages in last 7 Days", :style => {:color => "FFF"})
f.chart( :backgroundColor => '#3F4955' )
# --- the background images wont work
# f.chart( :plotBackgroundImage => "/images/gb.gif" )
# --- get this shit not to run -> replace it with the giv_me_date() function
# f.xAxis(:type => 'datetime', :dateTimeLabelFormats => {:day => "%e. %b"}, :labels => {:style => {:color => "FFF"}})
# f.xAxis(:type => 'datetime', :labels => {:style => {:color => "FFF"}, :formatter => %|function() {return Highcharts.dateFormat('%d %b %y', this.value );}|.js_code})
f.xAxis(:categories => giv_me_date , :labels => {:style => {:color => "FFF"}})
f.yAxis(:title => {:text => "Menge", :style => {:color => "FFF"}}, :labels => {:style => {:color => "FFF"}})
f.series(:name=>'Messages', :data=> mess)
f.legend(:itemStyle => {:color => "FFF"}, :itemHoverStyle => {:color => "FF0F"}, :itemHiddenStyle => {:color => "FFF"}, :borderWidth => nil, :layout => "vertical")
end
return message_graph
end
private
# write this small date function because http://www.highcharts.com/ref/#xAxis--dateTimeLabelFormats will not work
def giv_me_date
date = []
(1..7).each do |i|
date[i] = Time.now - (60 * 60 * 24)*(i-1)
date[i] = date[i].strftime("%d/%m")
end
return date.reverse
end
end
# now create in your controller.rb a Graph object
# g = CreateGraph.new
# @message_graph = g.init
# and insert it to your view
# <%= high_chart("message_chart", @message_graph) %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment