假设我有这个类(直接取自aasm文档):
class Job < ActiveRecord::Base
include AASM
aasm do
state :sleeping, :initial => true
state :running
state :cleaning
event :run do
transitions :from => :sleeping, :to => :running
end
event :clean do
transitions :from => :running, :to => :cleaning
end
event :sleep do
transitions :from => [:running, :cleaning], :to => :sleeping
end
end
end
我不太喜欢将状态机定义与我的类定义混合的事实(因为当然在实际项目中我会向Job类添加更多方法)。
我想在模块中分离状态机定义,以便Job类可以是以下内容:
class Job < ActiveRecord::Base
include StateMachines::JobStateMachine
end
然后我在app / models / state_machines中创建了一个job_state_machine.rb文件,内容类似于:
module StateMachines::JobStateMachine
include AASM
aasm do
state :sleeping, :initial => true
state :running
state :cleaning
event :run do
transitions :from => :sleeping, :to => :running
end
event :clean do
transitions :from => :running, :to => :cleaning
end
event :sleep do
transitions :from => [:running, :cleaning], :to => :sleeping
end
end
end
但这不起作用,因为AASM被包含在不在Job类中的模块中......我甚至尝试将模块更改为:
module StateMachines::JobStateMachine
def self.included(base)
include AASM
aasm do
state :sleeping, :initial => true
state :running
state :cleaning
event :run do
transitions :from => :sleeping, :to => :running
end
event :clean do
transitions :from => :running, :to => :cleaning
end
event :sleep do
transitions :from => [:running, :cleaning], :to => :sleeping
end
end
end
end
但仍然没有用......任何提示或建议都非常感激。
谢谢, 纳齐奥西隆
编辑:
感谢Alto,正确的解决方案就是:
module StateMachine::JobStateMachine
def self.included(base)
base.send(:include, AASM)
base.send(:aasm, column: 'status') do
....
end
end
end
显然要记得在主类中包含状态机定义,如下所示:
include StateMachine::JobStateMachine
答案 0 :(得分:7)
你这么简单吗?
module StateMachines::JobStateMachine
def self.included(base)
base.send(:include, AASM)
aasm do
...
end
end
end