Topic: Refactoring for models with state_machine

I have 3 models that all have the exact same state_machine states and actions. I'd like to DRY up the code and i've tried inheriting those classes from a StatefulModel class but that didnt seem to work very well with ActiveRecord. Any ideas?

Re: Refactoring for models with state_machine

I also tried putting the state_machine stuff inside of a module but that didn't seem to work either. I assume it has to be possible, i'm just not doing it correctly!

Re: Refactoring for models with state_machine

You could try something like this:

  include StatefulModel

  #stateful_model.rb
  module StatefulModel
    def self.included(calling_klass)
      calling_klass.extend do
       # class level stuff (like state_machine)
      end
    end
  end


I'm a little sketchy on the details, I dont have sample code in front of me, but we've used something similar at work to add class methods through includes.

Re: Refactoring for models with state_machine

thanks for the reply but that didn't seem to work. I'll see if I can uncover some other ideas from the Ruby Way. Any more advice is more than welcome!

Re: Refactoring for models with state_machine

module StatefulModel
  def self.included(base)
    base.extend ScottBarron do

      acts_as_state_machine :initial => :active, :column => :state_machine
      state :active
      state :suspended, :enter => :log_suspension
      state :deleted,   :enter => :do_delete

      event :suspend do
        transitions :from => :active, :to => :suspended
      end
     
      event :delete do
        transitions :from => [:active, :suspended], :to => :deleted
      end

      event :unsuspend do
        transitions :from => :suspended, :to => :active
      end
    end
  end
 
  protected
   
    # logs suspension event to production log
    def log_suspension
      #logger.info
    end
   
    # changes attributes to deleted and records event to production log
    def do_delete
      self.deleted_at = Time.now.utc
      #logger.info "#{self.class}: Suspended #{}"
    end
end


--maybe this will help illustrate what I mean? Also, on various models I just want to do:
include StatefulModel and have all of those events/states

Re: Refactoring for models with state_machine

looks like the newest version of the plugin has addressed this concern. I will learn from their example smile