Finnjon
Finnjon

Reputation: 671

Where should I put methods to be used by multiple controllers in rails?

I have an admin controller and view to manage admin tasks. Many of those tasks are very similar to tasks conducted in my two main model-backed controllers, Users and Materials. I'm trying to dry up my code so I want to put it somewhere, but where?

For example:

As an admin I can delete a Material from my admin view but so can a User from their material view. I have almost identical code for this in both the admin and material controllers with the only exception that the redirect goes to a different place.

Upvotes: 2

Views: 638

Answers (2)

klaffenboeck
klaffenboeck

Reputation: 6377

The Rails4 way is to use Concerns, even though there is some discussion going on about it. Still, I like this approach, even though most of the material you find will be more about models than about controllers.

A simple example

If you are on Rails 3 (as your tag implies), just add a concerns-folder into your controllers-folder and add it to your autoload-path:

#config/application.rb
config.autoload_paths += %W(#{config.root}/app/controllers/concerns)

For instance, I have something like this in app/controllers/concerns/can_can_sanitizer.rb

module CanCanSanitizer
  extend ActiveSupport::Concern

  included do
    before_filter do
      resource = controller_path.singularize.gsub('/', '_').to_sym
      method = "#{resource}_params" 
      params[resource] &&= send(method) if respond_to?(method, true)
    end
  end
end

I include this into my application_controller just like any other module:

include CanCanSanitizer

Admittedly, not the best use-case, but it should give you a headstart.

Upvotes: 2

Billy Chan
Billy Chan

Reputation: 24815

If the AdminsController is inherited from UsersController, you can put such methods in UsersController, judging the difference from method arguments or controller name or code before super.

If Admin and User has no inheritance, you can create a separate module and get both Admin and User to include it.

Upvotes: 1

Related Questions