AASM: proper syntax for a guard callback

2.5k Views Asked by At

Here is my example code:

class Foo < ActiveRecord::Base
  include AASM
  aasm_column :status
  aasm_initial_state :start_state

  aasm_state :start_state
  aasm_state :state_two
  aasm_state :end_state

  aasm_event :move_to_two, :guard => :guard_callback, :after => :after_callback do
    transitions :from => :start_state, :to => :state_two
  end

  def guard_callback
    puts "executing guard callback..."
    false
  end

  def after_callback
    puts "executing after callback..."
  end

This is a toy representation of what my code looks like. I'm only returning false from the guard callback to test the behavior of NOT executing the transition or the after. Here is the code I call in my test

foo = Foo.new
foo.move_to_two!
puts "foo's current status: #{foo.status}"

Here's the output

executing after callback...
foo's current status: state_two

Notice that the guard never gets called...

Am I putting the guard in the wrong place? Am I mistaken that returning false will halt the transition? Does halting the transition also cause the after callback to be ignored? Or will it always execute the after no matter what?

If this last thing is true, how do I pass state into that callback?

thanks in advance, and let me know if you need more information...

jd

1

There are 1 best solutions below

0
On

OK, I figured it out (the whole "as soon as you ask, you find the answer" thing)...the :guard goes on the transitions themselves as such:

aasm_event :move_to_two, :after => :after_callback do
  transitions :from => :start_state, :to => :state_two, :guard => :guard_callback
end