views:

354

answers:

2

Is it possible to invoke a method when the initial state is entered when using the AASM Gem? I'd like the spam_check method to get called when a comment is submitted, but it doesn't seem to work.

class Comment < ActiveRecord::Base
  include AASM

  aasm_column :state
  aasm_initial_state :submitted
  aasm_state :submitted, :enter => :spam_check
  aasm_state :approved
  aasm_state :rejected

  aasm_event :ham do
    transitions :to => :approved, :from => [:submitted, :rejected]
  end

  aasm_event :spam do
    transitions :to => :rejected, :from => [:submitted, :approved]
  end

  def spam_check
    # Mark the comment as spam or ham...
  end
end
+1  A: 

How about using the initialize method?, it's not as self-documenting but should work.

krusty.ar
+1  A: 

My guess is, that since the spam checking is taking place just before the initial state is set, your :spam and :ham transitions can't be executed, since the :from condition says the state should be :submitted, :rejected or :approved (but in the fact, it's nil). Initial state is set on before_validation_on_create callback, so what about trying it like this?

after_validation_on_create :spam_check

aasm_event :spam_check do
  transitions :to => :approved, :from => [:submitted, :rejected], :guard => Proc.new {|c| !c.spam?} 
  transitions :to => :rejected, :from => [:submitted, :approved], :guard => 'spam?'
end

def spam?
  # your spam checking routine
end

This should fire the spam_check event after the initial_state was set and will set ste state to either :approved or :rejected.

Milan Novota
Thanks. I realised after I posted the question that it makes sense to only check if the comment is spam after it passes validation.
John Topley