Search code examples
ruby-on-railsmodel-view-controllerdrawingcode-organization

Where should I put chart-drawing code in Rails?


I've got some custom Ruby code for generating a chart (which will generally be displayed as an inline SVG in a "show" view) based on the contents of the model.

I'm wondering where I should put the drawing code. As I see it, I could:

  1. Put it in the model, so I can call @my_object.chart_as_svg in my view ... but this would diverge from MVC
  2. Put it in a view, like show.svg.erb, and let my controller respond to format.svg
  3. Put it in the controller as a separate action
  4. Put it in a helper...

What's the prevailing wisdom on this?


Solution

  • If you think you might reuse the charting code for other things, make it a class, put it in lib and set it up so you can do something like this in your controller:

    @chart = MyChart.new(:data => @my_object.data_method, :title => 'Foo Chart', ....)
    send_data @chart.to_svg, ...
    

    ..

    This way you can extend it with other options, add .to_png, etc without mucking up your model.