2014-08-27 17 views
5

假設我有這個類(直接從AASM資料爲準):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類添加更多方法)。

我想狀態機定義的模塊中分離出來,這樣的作業類可以沿着線的東西:

class Job < ActiveRecord::Base 
    include StateMachines::JobStateMachine 
end 

然後我創建了應用程序/模型/ 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不是在招聘類...我甚至試過模塊更改爲:

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 

但它仍然不工作...任何暗示或建議是非常感激。

感謝, 納齊奧西隆


編輯:

由於奧拓,正確的解決辦法是這樣的:

module StateMachine::JobStateMachine 

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

    base.send(:aasm, column: 'status') do 
    .... 
    end 
    end 
end 

,顯然要記住,在狀態機定義主類如下:

include StateMachine::JobStateMachine 

回答

7

難道你不能簡單地做到這一點?

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

    aasm do 
     ... 
    end 
    end 
end 
+0

謝謝alto,你把我放在正確的道路上,我會相應地修改我的問題,以便將來誰來這裏 – Gnagno 2014-08-29 14:12:34