ruby – AASM:将状态机定义与类定义分开
发布时间:2020-12-17 03:29:11 所属栏目:百科 来源:网络整理
导读:假设我有这个类(直接取自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
假设我有这个类(直接取自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,:to => :sleeping end end end 但这不起作用,因为AASM被包含在不在Job类中的模块中……我甚至尝试将模块更改为: module StateMachines::JobStateMachine def self.included(base) include AASM aasm do state :sleeping,: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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |