Run a Rails controller before the before_action callback after the others

Is there an easy way to add to the list before_action for the controller in rails, so that other callbacks before_actionadded later will be executed before and after my callback?

My use is that I worry about what other controllers will include, and I want the controllers included in it to be able to add their own methods before_action, but then one of my methods is called after all of them, but before actual action.

Since this is a rather large code base with a bunch of developers, for ease of use, I don’t want every user to have to do this prepend_before_actionor have to remember includemy module after they declared their callbacks and not at the top of the class.

I am sure there is no built-in way to do this, and I am not very familiar with ruby ​​metaprogramming. But is there a way to connect to the internal functions of the callback list when callbacks are started and add a new callback to the end or something like that?

+4
source share
1 answer

- ActiveSupport::Callbacks , , CallbackChain#append_one , , before_action remove_duplicates , . , before_action:

module MyModule
  extend ActiveSupport::Concern

  included do
    before_action :my_last_callback
  end

  class_methods do
    def before_action(*args, &blk)
      method(:before_action).super_method.call(*args, &blk)
      method(:before_action).super_method.call(:my_last_callback)
    end
  end

  def my_last_callback
    # do stuff after all before_action callbacks
  end
end

before_action, , , my_last_callback . ( / , , , O (N ^ 2) O (N) , - , ).

0

Source: https://habr.com/ru/post/1666316/


All Articles