【问题标题】:AASM: Separating the state machine definition from the class definitionAASM:将状态机定义与类定义分开
【发布时间】:2014-08-27 15:07:40
【问题描述】:

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

【问题讨论】:

    标签: ruby module aasm


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢你,你让我走上了正确的道路,我会为将来来这里的人相应地修改我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 2013-10-15
    相关资源
    最近更新 更多