Upon sign in, I have my SessionsController run an after_action to reset certain user columns. In another controller, I want to do the same after_action on create and update.
It's easy enough to just copy and paste the same code into both controllers, but I know that one day I'll make a change in one controller and forget to update the other.
Is there any way to call the same method as an after_action from different controllers?
There is several ways to do what you want:
after_action
callbackafter_action
callbackImplementation:
class ApplicationController < ActionController::Base
# ...
def clean_user_columns
raise 'No user connected!' unless current_user.present?
do_some_stuff
end
Usage:
class SessionsController < ApplicationController
after_action :clean_user_columns
Implementation:
# file created here: /lib/clean_user_columns_after_action.rb
# you will need to restart your server to see the changes of this file
module CleanUserColumnsAfterAction
def clean_user_columns
do_some_stuff
end
end
Usage:
class SessionController < ApplicationController
include CleanUserColumnsAfterAction
after_action :clean_user_columns
Conclusion: In my opinion, the Option #2 is the way to go:
include CleanCleanUserColumnsAfterAction
line.lib/controllers/
to contain every shared pieces of code of your controllers (if so, don't forget to rename your module to Controllers::CleanUserColumnsAfterAction
in the module definition + include
statements).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With