views:

87

answers:

2

Hi folks, i have a function that converts an array to a hash which i would like to use across all the model, controller and view files in the rails app.

Does this violate some core design principle, or am i missing something really obvious?

UPDATE: This is actually a software engineering question. I want to understand why some "convenient" things are not allowed in rails, and i suspect it is precisely because they do not want us to do it

A: 

I think you are: views should not need that method. The controller ought to do it and pass it along to the view for display. The controller or, better yet, service layer might apply that method to a model object, but there's little reason for a model object to know about it.

duffymo
+1  A: 

This is likely actually a bad practice. It'd likely be better to instead always work with arrays and hashes in your controllers and models and if necessary convert them in the view to the alternative.

That is, if the data is natively represented as a array throughout your application work with it that way and if required to be a hash in the view either convert it first and assign it or convert it in the view using a helper.

View global helpers go in: helpers/application_helper.rb

If you must call a helper from a controller you can still define it there and I believe you can do:

def Something
  ....
  hashData = @template.helper(arrayData)
end

Calling helpers in a model is REALLY not a good idea, there's no point.

As a final note, encapsulating this logic in a library would likely be ideal, your controllers can call a library & your view helpers can as well.

Matt S