atw
atw

Reputation: 5840

Rails: DRYing up before_action

I have a few controllers:

class First < ApplicationController
   before_action: do_this
   before_action: do_this_too
end

class Second < ApplicationController
  before_action: do_this
  before_action: do_this_too
end

class Third < ApplicationController

end

Two of the controllers have the same before_action's method. How do I dry up this code so that the First and Second class use the before_action's in one location but not the Third class?

I am thinking of some kind of class inheritance solution. Any ideas? In my real world example I have more classes with multiple identical before_actions on each?

Upvotes: 2

Views: 476

Answers (1)

Lucas Moulin
Lucas Moulin

Reputation: 2530

I believe that it's better to keep it the way it is. If you move these before_action to a module or something like that it will make your controller a lot harder to read and to understand what's happening.

In other words, you would DRY your controllers, but would also violate the KISS principle (Keep It Simple).

But if you want to do this anyway, here's how:

module SharedBeforeActions
  def self.included(base)
    base.before_action :do_this
  end

  def do_this
    # Your filter definition here
  end
end

class Third < ApplicationController
  include SharedBeforeActions
end

Finally you would have to config Rails to load your module:

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

Upvotes: 4

Related Questions