views:

240

answers:

1

There are 2 methods I want to call after every state transition. Right now I'm doing:

  aasm_event :nominate_for_publishing, :before => [:set_state_last_updated_by, :set_state_updated_at] do
    transitions :to => :under_review, :from => [:work_in_progress]
  end

  aasm_event :publish, :before => [:set_state_last_updated_by, :set_state_updated_at] do
    transitions :to => :published, :from => [:work_in_progress, :under_review], :guard => :is_publishable?
  end

  aasm_event :unpublish, :before => [:set_state_last_updated_by, :set_state_updated_at] do
    transitions :to => :work_in_progress, :from => [:published, :under_review]
  end

Obviously this isn't the best approach. I'm duplicating code, and more fundamentally, I'm associating callbacks with specific transitions when they really apply to the state machine as a whole. What's a better way to handle this?

+2  A: 

Why not just use dirty attributes to check if the state has been changed on save?

Like so,

class Model > ActiveRecord::Base

  before_save :set_state_updates

  private

  def set_state_updates
    if state_changed?
      set_state_last_updated_by
      set_state_updated_at
    end
  end 

end
Ben
This sounds basically right except 1) it should be `before_save`, no? 2) this kind of breaks the aasm abstraction insofar as it doesn't require you to change state with the aasm events (i.e., this will still work if you access the `state` attribute directly)
Horace Loeb
1) Yeah probably, edit to reflect that 2) I know, but its the best solution I could think of :(
Ben