Implement a conditional state machine for a rails model

352 views Asked by At

I have a rails model called Creative that implements a workflow using the aasm gem. Currently my model has just one workflow implemented in it.

I have a business scenario that will require me to implement another workflow in the same model which which will be activated if a boolean value on the model is true.

I see 2 approaches that could be viable options

  • Create a new model that uses the same table name as Creative and implement the workflow there
  • Implement the workflow in the same model using a separate column to store the states for the second workflow and use its method depending on my boolean value

What would be a good design that could be implemented here?

I understand this is a very open ended question and would love to get suggestions if anyone has come across such a scenario

1

There are 1 answers

1
Deepak Mahakale On

I think something like this should work.

event :promote do
  transitions :from => [:pending], :to => :in_progress, :guard => :boolean_check?
  transitions :from => [:pending], :to => :done
end

event :complete do
  transitions :from => [:in_progress], :to => :done, :guard => :boolean_check?
end

private

def boolean_check?
  self.boolean_column
end

If the boolean value is true the flow will be

pending > in_progress > done

else

pending > done

NOTE: This might get complex if let's say you have 3-4 workflows.

It's ok till you have 2 workflows