views:

188

answers:

5

I want to share code not related to views between several controllers in my Rails app. Where in the directory structure should I place it?

EDIT: the code in question if something all controllers use to determine how they render the model data

+7  A: 

If the code is something like modules with utility methods in these could be placed in the lib folder. Alternatively you could create a common superclass for some of your controllers if they share behaviour.

Please post an example of the kind of code you're thinking of.

mikej
A: 

Personally i think its fine, if its controller related to put it in your controllers directory, but, labelled as a module, e.g. app/controllers/what_am_i_module.rb since it is specific to the application in development.

lib seems like a place to me where i would put framework/core enhancements or monkey patches which are non-specific to the application.

Omar Qureshi
+5  A: 

If it's "something all controllers use", I would place it in a base class used by all controllers. The "application_controller" comes to mind.

Pete
+1 Sounds like application_controller.rb to me too.
cakeforcerberus
+1  A: 

I have been creating modules in lib to provide code to other classes.

Here's an abbreviated example module that defines values for views that can be instantiated from different controllers.

module ControllerDefaultValues
  def default_value_for_some_controller()
    @controller_name = "some_controller"
  end
end

To use this, simply include the module in your class:

class SearchesController
  include ControllerDefaultValues
  #
  def search_some_controller
    default_value_for_some_controller()
    render(:partial => "search_results")
  end
end

The main benefit of this method is it keeps your controllers directory focused on controllers and your models directory focused on logic.

A: 

If it's going to be used by all your controllers, stick it in application_controller.rb

All your controllers inherit from ApplicationController, so they'll all have access to them.

JimNeath