Mateus Carvalho
Mateus Carvalho

Reputation: 41

Is there a way using AASM with states and transitions configured by user?

I am using AASM with rails and I have been searching around for a solution for my problem, i need to make a state machine system configured by user.

Imagine this scenario:

  1. the user visit the States CRUD page
  2. the user creates a new state X and a new state Y for Project model
  3. the user creates a transition from state X to state Y for Project model
  4. the user visits Project show page
  5. the user can switch between the states he created for Project model

Is there an easy way to implement these cases using AASM?

I imagined something like this:

class Project < ActiveRecord::Base
  include AASM

  aasm do
         State.where(model_name: 'Project').each do |database_state|
           state database_state[:name], database_state[:initial]
         end

         Event.where(model_name: 'Project').each do |database_event|
           ...
         end
  end

end

Upvotes: 1

Views: 616

Answers (1)

Mateus Carvalho
Mateus Carvalho

Reputation: 41

here is the final module file, it works like how I planned:

module WorkflowModule 
    def self.included(base)
        base.send(:include, AASM)
        base.send(:aasm, column: 'aasm_state', no_direct_assignment: false) do  
            start_aasm(base)
        end
    end

    def start_aasm(base)
        State.where(entity: base.name.downcase).each_with_index do |state_database, index|
            if index == 0
                state state_database.name.to_sym, :initial => true
            else
                state state_database.name.to_sym
            end
        end
        Transition
            .joins(:workflow)
            .where(workflows: { entity: base.name.downcase})
            .each do |transition_database|
                event transition_database.name.to_sym do
                    transitions :from => State.where(state_from_id: transition_database.state_from_id).name.to_sym,
                                :to => State.where(state_to_id: transition_database.state_to_id).name.to_sym
                end
        end
    end
end

here is my full example: https://github.com/mtsbarbosa/base_web_rails_app

Upvotes: 1

Related Questions