Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use the same `before_action` filter in multiple controllers

In a Rails app, I have a before_action filter that sends a webhook message. Since I have a few controllers that I want the before_action to act on, is there a good way to make it a module and prepend it?

My current logic is:

# first_controller.rb:
before_action :do_something
def do_something
 #same logic
end

# second_controller.rb:
before_action :do_something
def do_something
 #same logic
end

# third_controller.rb:
before_action :do_something
def do_something
 #same logic
end
like image 430
user2309838 Avatar asked Jan 25 '26 05:01

user2309838


2 Answers

If your controllers inherit from ApplicationController, You can do the following:

class ApplicationController < ActionController::Base
  def do_something
   #same logic
  end
end

class FirstController < ApplicationController
  before_action :do_something
end
class SecondController < ApplicationController
  before_action :do_something
end
class ThirdController < ApplicationController
  before_action :do_something
end

Or you can make your own parent controller, eg. DoSomethingController

class DoSomethingController < ApplicationController
  before_action do_something

  def do_something
   #same logic
  end
end

class FirstController < DoSomethingController
end
class SecondController < DoSomethingController
end
class ThirdController < DoSomethingController
end

Or you can use @code_aks's answer https://stackoverflow.com/a/59846330/8554172 to make a module and include it.

like image 96
Feifei Xiong Avatar answered Jan 27 '26 18:01

Feifei Xiong


Yes, it is good to use DRY here. If your controllers do have same parent class you can place that method in there. If not it is good practice to move this method to the module and include it with reusing.

like image 25
Roman Alekseiev Avatar answered Jan 27 '26 17:01

Roman Alekseiev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!