AASM improvements
While using great acts_as_state_machine plugin at work I needed to make some improvements to it. This example illustrates new :log_transitions option to acts_as_state_machine directive and how it can be used to audit transitions to action_history_items table – I like to have an action history log for objects that travel by states.
I’d be happy to publish my improvements but don’t know yet in what form.
class ExpenseClaim < ActiveRecord::Base
has_many :action_history, :class_name => 'ActionHistoryItem', :as => :document,
:order => 'id desc'
acts_as_state_machine :initial => States::DRAFT, :log_transitions => true
state States::DRAFT, :owner => Roles::AUTHOR
state States::MANAGER_APPROVAL_REQUIRED, :owner => Roles::APPROVING_MANAGER
state States::REJECTED_BY_FINANCE, :owner => Roles::APPROVING_MANAGER
#...
event :send_for_manager_approval do
transitions :from => States::DRAFT, :to => States::MANAGER_APPROVAL_REQUIRED
transitions :from => States::REJECTED_BY_MANAGER,
:to => States::MANAGER_APPROVAL_REQUIRED
end
event :approve do
transitions :from => States::MANAGER_APPROVAL_REQUIRED,
:to => States::FINANCE_APPROVAL_REQUIRED
transitions :from => States::FINANCE_APPROVAL_REQUIRED,
:to => States::APPROVED
transitions :from => States::REJECTED_BY_FINANCE,
:to => States::FINANCE_APPROVAL_REQUIRED
end
#...
def log_transition(from, to, event, opts)
user = self.updated_by
raise "user is not set" if user.nil?
as_role = self.class.states_table[from].opts[:owner]
action_history << ActionHistoryItem.new({:from_state => from.to_s,
:to_state => to.to_s, :action => event.to_s, :user_id => user.id,
:as_role => as_role.to_s, :at => Time.now})
end
#...
end
Update
Here’s the patch mentioned: http://pastie.caboo.se/151469, looks to be perfect way to publish it for now )
More info
Acts as State Machine:
http://rubyi.st/2006/1/21/acts-as-state-machine
Ruby on Rails Finite State Machine Plugin: acts_as_state_machine >> rails symphonies:
http://rails.aizatto.com/2007/05/24/ruby-on-rails-finite-state-machine-plugin-acts_as_state_machine/
Filed under: acts_as_state_machine, rails, ruby | 6 Comments
Search
-
You are currently browsing the Artem Vasiliev's Weblog weblog archives.
Looking forward to when you do publish…. I could do with this i some code I’m working on.
Scott told that he’s interested also so maybe it will find its way to AASM’s trunk someday.
If you want it earlier I can send the patch to you by email.
Hello, is it possible to send me the patch? I’ve been trying to build an audit trail in aasm, interested to see how you did it. Thanks.
Hi there
Your changes to AASM look perfect for a project I’m starting. Any plans to host them as a fork on github? If not, do you mind if I set that up?
Regards
David
Yes, sure, go ahead! Just in case, I’m artemv at github.
A state pattern based alternative to AASM: http://github.com/dcadenas/active_record_state_pattern