What is purpose of around_create callback in Rails Model?

前端 未结 6 1987
野的像风
野的像风 2021-02-05 15:42

when is around_create callback code executed, in what situations we should use it?

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 16:03

    Just found one use case for me:

    Imagine a situation with polymorphic watcher and the watcher in some cases needs to perform action before save and in other cases after it.

    With around filter you can capture save action in a block and run it when you need.

    class SomeClass < ActiveRecord::Base
    
    end
    
    class SomeClassObserver < ActiveRecord::Observer
      def around_create(instance, &block)
        Watcher.perform_action(instance, &block)
      end
    end
    
    # polymorphic watcher
    class Watcher
      def perform_action(some_class, &block)
        if condition?
          Watcher::First.perform_action(some_class, &block)
        else
          Watcher::Second.perform_action(some_class, &block)
        end
      end
    end
    
    class Watcher::First
      def perform_action(some_class, &block)
        # update attributes
        some_class.field = "new value"
    
        # save
        block.call
      end
    end
    
    class Watcher::Second
      def perform_action(some_class, &block)
        # save
        block.call
    
        # Do some stuff with id
        Mailer.delay.email( some_class.id )
      end
    end
    

提交回复
热议问题