我怎样才能跳过回调

时间:2017-01-31 08:43:29

标签: 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

如果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

但我认为这是多余的,因为应该多次进入redis。

1 个答案:

答案 0 :(得分: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

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