geekq / workflow

Ruby finite-state-machine-inspired API for modeling workflow
MIT License
1.75k stars 207 forks source link

Can't pass method symbol name to if #183

Closed mhmaguire closed 2 years ago

mhmaguire commented 8 years ago

Condition on an event doesn't take method name symbol as indicated in the documentation

class Thing < ActiveRecord::Base
    include Workflow 

    workflow do 
        state :on do 
            event :turn_off, transitions_to: :off
        end

        state :off do 
            event :turn_on, transitions_to: :on, if: :has_power
        end
    end

    def has_power
        power > 0
    end

    def turn_on
        halt!('cannot turn on') unless check
    end
end

Thing.new # => TypeError: condition must be nil or callable (eg. a proc or lambda)

with 1.2.0

mhmaguire commented 8 years ago

hmmm i see that source for 1.2.0 doesn't support symbol method names so perhaps this is a non issue

dan-jensen commented 3 years ago

Yeah, the documentation still needs to be corrected. The conditional event transitions should only show the proc example.

For anyone who wants to use the same proc in multiple places (like an instance method), you can store the proc to a constant like this:

TRANSITIONS_TO_ANOTHER_STATE = proc do |record|
  record.should_transition?
end

workflow do
  state :default do
    event :something_happened, transitions_to: :another_state, if: TRANSITIONS_TO_ANOTHER_STATE
  end
end