Module: Saulabs::Reportable::SparklineTagHelper

Defined in:
lib/saulabs/reportable/sparkline_tag_helper.rb

Instance Method Summary collapse

Instance Method Details

#sparkline_tag(data, options = {}) ⇒ String

Renders a sparkline with the given data.

Examples:

Rendering a sparkline tag for report data


<%= sparkline_tag(User.registrations_report, :width => 200, :height => 100, :color => '000') %>

Parameters:

  • data (Array<Array<DateTime, Float>>)

    an array of report data as returned by Report#run

  • options (Hash) (defaults to: {})

    options for the sparkline

Options Hash (options):

  • :width (Fixnum) — default: 300

    the width of the generated image

  • :height (Fixnum) — default: 34

    the height of the generated image

  • :line_color (String) — default: '0077cc'

    the line color of the generated image

  • :fill_color (String) — default: 'e6f2fa'

    the fill color of the generated image

  • :labels (Array<Symbol>) — default: []

    the axes to render lables for (Array of :x, :y, :r, :t; this is x axis, y axis, right, top)

  • :alt (String) — default: ''

    the alt attribute for the generated image

  • :title (String) — default: ''

    the title attribute for the generated image

Returns:

  • (String)

    an image tag showing a sparkline for the passed data



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/saulabs/reportable/sparkline_tag_helper.rb', line 36

def sparkline_tag(data, options = {})
  options.reverse_merge!({ :width => 300, :height => 34, :line_color => '0077cc', :fill_color => 'e6f2fa', :labels => [], :alt => '', :title => '' })
  data = data.collect { |d| d[1] }
  labels = ''
  unless options[:labels].empty?
    chxr = {}
    options[:labels].each_with_index do |l, i|
      chxr[l] = "#{i}," + ([:x, :t].include?(l) ? "0,#{data.length}" : "#{[data.min, 0].min},#{data.max}")
    end
    labels = "&chxt=#{options[:labels].map(&:to_s).join(',')}&chxr=#{options[:labels].collect{|l| chxr[l]}.join('|')}"
  end
  title = ''
  unless options[:title].empty?
    title = "&chtt=#{options[:title]}"
  end
  image_tag(
    "http://chart.apis.google.com/chart?cht=ls&chs=#{options[:width]}x#{options[:height]}&chd=t:#{data.join(',')}&chco=#{options[:line_color]}&chm=B,#{options[:fill_color]},0,0,0&chls=1,0,0&chds=#{data.min},#{data.max}#{labels}#{title}",
    :alt   => options[:alt],
    :title => options[:title]
  )
end