aasm/lib/aasm.rb

80 lines
1.9 KiB
Ruby
Raw Normal View History

require File.join(File.dirname(__FILE__), 'event')
2008-02-21 17:32:04 +00:00
require File.join(File.dirname(__FILE__), 'state')
require File.join(File.dirname(__FILE__), 'persistence')
2008-01-07 19:11:38 +00:00
module AASM
class InvalidTransition < Exception
end
2008-01-07 19:11:38 +00:00
def self.included(base) #:nodoc:
base.extend AASM::ClassMethods
AASM::Persistence.set_persistence(base)
2008-01-07 19:11:38 +00:00
end
module ClassMethods
2008-02-21 17:59:28 +00:00
def aasm_initial_state(set_state=nil)
if set_state
aasm_initial_state = set_state
else
@aasm_initial_state
end
2008-01-07 19:11:38 +00:00
end
def aasm_initial_state=(state)
@aasm_initial_state = state
end
2008-02-21 17:59:28 +00:00
def aasm_state(name, options={})
aasm_states << name unless aasm_states.include?(name)
self.aasm_initial_state = name unless self.aasm_initial_state
2008-01-07 19:11:38 +00:00
define_method("#{name.to_s}?") do
2008-01-08 14:39:00 +00:00
aasm_current_state == name
2008-01-07 19:11:38 +00:00
end
end
2008-02-21 17:59:28 +00:00
def aasm_event(name, &block)
unless aasm_events.has_key?(name)
aasm_events[name] = AASM::SupportingClasses::Event.new(name, &block)
end
2008-01-07 19:11:38 +00:00
define_method("#{name.to_s}!") do
2008-01-08 15:03:18 +00:00
new_state = self.class.aasm_events[name].fire(self)
unless new_state.nil?
self.aasm_current_state = new_state
true
else
false
end
2008-01-07 19:11:38 +00:00
end
end
def aasm_states
@aasm_states ||= []
end
2008-01-08 15:03:18 +00:00
def aasm_events
@aasm_events ||= {}
2008-01-07 19:11:38 +00:00
end
end
# Instance methods
2008-01-08 14:39:00 +00:00
def aasm_current_state
return @aasm_current_state if @aasm_current_state
if self.respond_to?(:aasm_read_state) || self.private_methods.include?('aasm_read_state')
@aasm_current_state = aasm_read_state
end
return @aasm_current_state if @aasm_current_state
self.class.aasm_initial_state
2008-01-07 19:11:38 +00:00
end
2008-01-08 14:39:00 +00:00
private
def aasm_current_state=(state)
@aasm_current_state = state
if self.respond_to?(:aasm_write_state) || self.private_methods.include?('aasm_write_state')
2008-02-21 16:15:40 +00:00
aasm_write_state(state)
2008-01-08 14:39:00 +00:00
end
end
2008-01-07 19:11:38 +00:00
end