Callbacks

around_transition Callback

  • Callbacks invoked around a transition so long as the given requirements match the transition
  • Wrap transitions, executing code both before and after

Defintion

  • Defined in the exact same manner as before/after callbacks except the transition must be yielded to in order to finish running it
  • If defining around callbacks using blocks, you must yield within the transition by directly calling the block (since yielding is not allowed within blocks):

    class Vehicle
      state_machine do
        around_transition do |block|
          Benchmark.measure { block.call }
        end
    
        around_transition do |vehicle, block|
          logger.info "vehicle was #{state}..."
          block.call
          logger.info "...and is now #{state}"
        end
    
        around_transition do |vehicle, transition, block|
          logger.info "before #{transition.event}: #{vehicle.state}"
          block.call
          logger.info "after #{transition.event}: #{vehicle.state}"
        end
      end
    end
    

    referencing the block is similar to doing so within an actual method definition in that it is always the last argument.

  • if you're defining around callbacks using method references, yield like normal:

    class Vehicle
      state_machine do
        around_transition :benchmark
        ...
      end
    
      def benchmark
        Benchmark.measure { yield }
      end
    end
    

See before_transition for all possible configurations for defining callbacks.

results matching ""

    No results matching ""