Search code examples
ruby-on-railsgruff

How can I generate images in real-time using Ruby on Rails and Gruff?


I draw bar graphs in my app using gruff. In one view, 'compare', I want to show one graph for every 'step' my 'project' has. I imagine it something like this:

image_tag graph_step_path(step)

I've created a 'graph' action in the step controller and included a route. But now I'm kind of lost. How can my controller action return the correct image path to the image_tag function? Doing 'return' doesn't feel right. Or could I somehow directly include the image blob generated by gruff?

edit:

I've created a helper function that creates the graph and returns the file path.


Solution

  • In your controller method you want to return the actual image instead of a path. Writing the images to disk for every request would be very slow. The send_data method in rails is used to do this.

    send_data(g.to_blob, :filename => "any.png", :type => 'image/png', :disposition=> 'inline')
    

    g is your gruff instance. The filename doesn't matter at all. The src of your image tag should just be the specific controller method that generates your graph. You can use normal url helpers to generate this.