我怎样才能跳过回调

itx*_*itx 3 ruby-on-rails ruby-on-rails-4

我有控制器看起来像

class BarsController < ApplicationController
   after_action :some_method, only: [:index]

   def index
      get_cache = $redis.get('some_key')
      if get_cache.present?
          # i want to skip after_action callback in here
      else
          # other stuff
      end
   end
end
Run Code Online (Sandbox Code Playgroud)

after_action :some_method如果get_cache存在,我该如何跳过?我知道我可以像这样有条件地做到这一点

class BarsController < ApplicationController
   after_action :some_method, only: [:index], unless: :check_redis

   def index
      get_cache = $redis.get('some_key')
      if get_cache.present?
          # i want to skip after_action callback in here
      else
          # other stuff
      end
   end


   private

   def check_redis
     $redis.get('some_key')
   end
end
Run Code Online (Sandbox Code Playgroud)

但我认为这是多余的,因为应该多次获得redis.

Arg*_*nus 5

这应该工作:

class BarsController < ApplicationController

   after_action :some_method, only: [:index], unless: :skip_action?

   def index
      get_cache = $redis.get('some_key')
      if get_cache.present?
          @skip_action = true
          # i want to skip after_action callback in here
      else
          # other stuff
      end
   end


   private

   def skip_action?
     @skip_action
   end
end
Run Code Online (Sandbox Code Playgroud)

您也可以使用attr_accessor :skip_action而不是私有方法,因为控制器只是对象.

  • 还有一种情况是`some_method`可能会挽救:`返回if @skip_action`作为该方法的第一行. (2认同)