AASM: splitting a state machine definition from a class definition

Suppose I have this class (taken directly from the aasm documentation):

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 

I don’t really like the fact that I have my definition of a state machine mixed with my definition of a class (since, of course, in a real project I will add more methods to the Job class).

I would like to separate the definition of the state machine in the module so that the Job class can be something along the line:

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

Then I created a job_state_machine.rb file in app / models / state_machines with content similar to:

 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 

but this does not work, because AASM is included in the module not in the Job class ... I even tried to change the module to:

 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 

but still it doesn’t work ... any hint or suggestion is greatly appreciated.

Thanks Ignazio


EDIT:

Thanks to Alto, the correct solution is the following:

 module StateMachine::JobStateMachine def self.included(base) base.send(:include, AASM) base.send(:aasm, column: 'status') do .... end end end 

and obviously don't forget to include the definition of the main computer in the main class as follows:

 include StateMachine::JobStateMachine 
+5
source share
1 answer

Could you just do it?

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

Source: https://habr.com/ru/post/1201243/


All Articles