Bruno Antunes
Bruno Antunes

Reputation: 2262

Where to place Rails code that is not a model, view, controller or helper?

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

Upvotes: 8

Views: 727

Answers (5)

Jim Neath
Jim Neath

Reputation: 1217

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.

Upvotes: 0

Kevin McFadden
Kevin McFadden

Reputation: 139

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.

Upvotes: 2

Pete
Pete

Reputation: 10680

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.

Upvotes: 5

Omar Qureshi
Omar Qureshi

Reputation: 9093

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.

Upvotes: 0

mikej
mikej

Reputation: 66263

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.

Upvotes: 9

Related Questions