2008-01-07 20:07:38 +00:00
|
|
|
require File.join(File.dirname(__FILE__), 'event')
|
2008-02-21 17:32:04 +00:00
|
|
|
require File.join(File.dirname(__FILE__), 'state')
|
2008-01-07 20:07:38 +00:00
|
|
|
|
2008-01-07 19:11:38 +00:00
|
|
|
module AASM
|
2008-01-07 20:07:38 +00:00
|
|
|
class InvalidTransition < Exception
|
|
|
|
end
|
|
|
|
|
2008-01-07 19:11:38 +00:00
|
|
|
def self.included(base) #:nodoc:
|
|
|
|
base.extend AASM::ClassMethods
|
|
|
|
end
|
|
|
|
|
|
|
|
module ClassMethods
|
|
|
|
def aasm_initial_state
|
|
|
|
@aasm_initial_state
|
|
|
|
end
|
|
|
|
|
|
|
|
def aasm_initial_state=(state)
|
|
|
|
@aasm_initial_state = state
|
|
|
|
end
|
|
|
|
alias :initial_state :aasm_initial_state=
|
|
|
|
|
|
|
|
def state(name, options={})
|
2008-02-21 17:54:42 +00:00
|
|
|
aasm_states << name unless aasm_states.include?(name)
|
2008-02-21 15:16:08 +00:00
|
|
|
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 15:16:08 +00:00
|
|
|
|
2008-01-07 20:07:38 +00:00
|
|
|
def event(name, &block)
|
2008-02-21 17:54:42 +00:00
|
|
|
unless aasm_events.has_key?(name)
|
|
|
|
aasm_events[name] = AASM::SupportingClasses::Event.new(name, &block)
|
|
|
|
end
|
2008-02-21 15:16:08 +00:00
|
|
|
|
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)
|
2008-02-21 17:11:25 +00:00
|
|
|
unless new_state.nil?
|
|
|
|
self.aasm_current_state = new_state
|
|
|
|
true
|
|
|
|
else
|
|
|
|
false
|
|
|
|
end
|
2008-01-07 19:11:38 +00:00
|
|
|
end
|
2008-01-07 20:07:38 +00:00
|
|
|
end
|
|
|
|
|
2008-02-21 17:54:42 +00:00
|
|
|
def aasm_states
|
|
|
|
@aasm_states ||= []
|
|
|
|
end
|
|
|
|
|
2008-01-08 15:03:18 +00:00
|
|
|
def aasm_events
|
2008-01-07 20:07:38 +00:00
|
|
|
@aasm_events ||= {}
|
2008-01-07 19:11:38 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2008-02-21 15:16:08 +00:00
|
|
|
# Instance methods
|
2008-01-08 14:39:00 +00:00
|
|
|
def aasm_current_state
|
2008-02-21 16:08:55 +00:00
|
|
|
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_read_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
|
2008-02-21 16:08:55 +00:00
|
|
|
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
|