views:

70

answers:

3

I try to be very good about keeping my view code and my controller code separate, but occasionally I run into situations where I need to use the same function in the controller and in the views. Where should I put this function so that I can access it from both the controller and the view?

+4  A: 

You can put it in a controller and make it available as a helper. If you need it to be available between multiple controllers and their views put in the application controller or other inherited controller:

helper_method :shared_function
mark
Exactly what I was looking for, Thanks!
Janak
A: 

I actually think a module is the best way to share code amongst controllers. Helpers are good if you want to share code amongst views. Helpers are basically glorified modules, so if you don't need view level access, I suggest placing a module in your lib folder.

If the code is really a set of utilities that doesn't need access to object state, I would consider putting it in a module to be called separately.

If the code needs state and is used in a subset of all controllers that are not very closely related, put it in a module and include it in necessary controllers.

-1. The first paragraph of this answer is copied verbatim from [this answer](http://stackoverflow.com/questions/128450/best-practices-for-reusing-code-between-controllers-in-ruby-on-rails/128771#128771), the other two from [this answer](http://stackoverflow.com/questions/128450/best-practices-for-reusing-code-between-controllers-in-ruby-on-rails/130821#130821). You've been quoting other people's answers without attribution a lot. Please stop doing that.
sepp2k
A: 

According to your situation, for example if the function return a standard Variable value that don't require any controls, you can call it directly from the view, on the contrary, if you have a function that return for example an array that requires controls it's judicious to call it from the the model before you show what you want on the view.

Amirouche Douda