Friday, November 13, 2009

Event callbacks in AASM

Having written about AASM in the past, first on Chaining state transitions with Acts As State Machine (aasm), and then again in Conditional state transitions with AASM, I thought I had AASM down rather pat.

However, when I tried adding a callback to the aasm_event, I ran into trouble. Quite simply, the callback never worked. Here's the first code:

Notice that the callback registration is in the aasm_event code block. It seemed reasonable that this would be part of the transition. When I determined that this was not working, I had a colleague review the code and we ended up both scratching our heads.

So, I cracked open the library and poked around. I saw the successful aasm_state call displaying the callback registration in the options portion of the method, but the options of the aasm_event were blank. Hmm!

Here are the method definitions for your edification:
aasm_state(name, options={})
aasm_event(name, options = {}, &block)

Well, it was pretty clear how to fix the problem; move the callback registration after the name argument and before the block. Here's the corrected code:
That's it! Have fun.