質問

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?

役に立ちましたか?

解決

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.

他のヒント

IMO: A little bit of everything! Going down your list:

  1. Your object has charts, so you should definitely have @obj.chart, but the chart isn't a part of the model - it may be created using model data, but it's not something that's a) restricted to that model or b) required by that model - so you do want it as part of a different package/module/object/etc
  2. The Ruby object of the chart, IMHO, shouldn't "know" how to turn itself into an HTML view. That's the job of a partial - _chart.svg.erb, _chart_typeB.svg.erb - but it should "know" how to transform its information - counts, averages, percentages, etc etc. Partials then consume those different "formats".
  3. I'm going to bet that at some point, you'll want to access the chart data directly via an API. Maybe you're turning your stuff into a platform, maybe you're doing AJAX updates to the current page; doesn't matter - you're going to eventually want some controller actions to directly access the chart data.
  4. You should take anything complex out of the view partial and turn them into helpers, but the partial should still be responsible for the "styling". That is, the partial should generate the smallest atomic view of the chart - just the chart, nothing but the chart - but the partial should be whatever else you generally want to show when you want to include the chart in a web page.

Edit: Reading the other answer a bit, I've got a different assumption: I'm assuming your taking the chart information and generating the picture via Javascript on the webpage, rather than generating a picture on the server and serving it. If you are doing the latter, I'd make it as part of the chart class - it's a different "format" into which the data can be transformed.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top