Integrate scruffy graph in rails view?

Hi everybody,

I’m using scruffy to create some graphs, and would like to integrate
them into a regular view (i.e. show them in an tag).

However, I get errors when using img_tag, or the image doesn’t load if
I try saving the graph to disk and then loading them in html.
Generating the graph and linking to it works, however then I only have
the graph open in a new window, whereas I’d like to use the graph as
an image inside an html page.

Any pointers on how to do this? I’ve searched around the ibrasten
website, and scruffy itself works just fine, but I’ve been unable to
locate any information on how to integrate scruffy into rails. Any
links would be most appreciated.

Thanks,
Elmar

Hi Elmar,

I’m using scruffy successfully in my project, here is what I do. I
have this in a helper of mine (you could put it in
application_helper.rb or wherever it’s fine for you)

def render_scruffy_graph(options = nil)
opts = make_options(options)
graph = Scruffy::Graph.new

add the Scruffy::Layers you would like to use

graph.add :bar, opts[:data]
graph.point_markers = opts[:markers]

graph.renderer = opts[:renderer]

graph.render(
:size => options[:size],
:min_value => opts[:data].first, # you might not need this one
:max_value => opts[:data].last, # you might not need this one
:theme => opts[:theme], # you might not need this one
:as => opts[:img_format],
:to => opts[:filename]
)
end

private

options specified here possibly

override options passed in parameter

def make_options(options = nil)
opts = options ? {}.merge(options) : {}
returning opts do |o|
# add o[:foo] = bar statements as you wish (look @ the options
that graph.render supports)
# you can specify :renderer and :theme like so
o[:renderer] = Scruffy::Renderers::YourRenderer.new
o[:theme] = Scruffy::Themes::YourTheme.new
end
end

There are definitely more flexible ways for generating your options,
but this did the trick for me …

Then in the view just call

<%= render_scruffy_graph %>

Hope this helps
Martin Gamsjäger

Oops forgot something,

Be sure not to use :as => “svg” if you want svg images. Scruffy’s
default is to use svg anyway, and if I recall correctly, something
went wrong when supplying :as => “svg”, :to => “blabla.svg”. Just use
the :to option if you want to render svg images to files.

cheers
Martin Gamsjäger