gpt4 book ai didi

ruby - AASM:将状态机定义与类定义分开

转载 作者:数据小太阳 更新时间:2023-10-29 07:05:36 25 4
gpt4 key购买 nike

假设我有这个类(直接取自 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

最佳答案

你不能简单地做到这一点吗?

module StateMachines::JobStateMachine
def self.included(base)
base.send(:include, AASM)

aasm do
...
end
end
end

关于ruby - AASM:将状态机定义与类定义分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25530739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com