Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can skip callback in action

I have controller looks like

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

How can I skip after_action :some_method if get_cache is present? I know I can do this with conditional like this

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

But I think that is redundant, because should multiple get to redis.

like image 752
itx Avatar asked Feb 16 '26 16:02

itx


1 Answers

This should work:

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

You can also use attr_accessor :skip_action instead of private method because controller is just object.

like image 67
Argonus Avatar answered Feb 19 '26 06:02

Argonus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!