3

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

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

You can try below code write the methods in a controller concern. For example:

# app/controllers/concerns/example_concern.rb
module ExampleConcern
 extend ActiveSupport::Concern

 protected
 def before_filter_1
   puts "from first before_filter_method"
 end

 def before_filter_2
   puts "from second before_filter_method"
 end
end

Now in the controller, include the module in the concern and call the methods using before_action as required. For example:

# app/controllers/examples_controller.rb
class ExamplesController < ApplicationController
  include ExampleConcern

  before_action :before_filter_1, only: [:action_a, :action_b, :action_c]
  before_action :before_filter_2, only: [:action_d, :action_e]

  def action_a
  end
  def action_b
  end
  def action_c
  end
  def action_d
  end
  def action_e
  end
end

Hope this will help you. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.