ruby-on-railsrubystate-machineaasm

Register callback for all transitions in AASM?


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?


Solution

  • 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