geekq / workflow

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

Specify different callback method #207

Closed robsdedude closed 5 years ago

robsdedude commented 6 years ago

I like the default way callbacks are handled (just calling the event name). However, I'd like to have an option to specify a different method. This is helpful in case the method is already in use. I just had the case: I wanted an event freeze but had to rename it to something longer and less readable because ActiveModel::Base already implements a method called freeze. I'd imagine the API to look something like this

class Article
  include Workflow
  workflow do
    state :initial do
      event :freeze, transitions_to: :frozen, callback: :my_freeze
    end
  end       
  def my_freeze
    puts 'this is called on article.freeze!'
  end
end
geekq commented 5 years ago

Another way to tell, what to do on a event, is to use a Ruby block. Block wins against the function naming convention.

state :initial do
  event :freeze, transitions_to: :frozen do
    puts 'this is called on article.freeze!'
  end
end

If your implementation is long, you can just call your function:

state :initial do
  event :freeze, transitions_to: :frozen do
    my_freeze
  end
end

There is also a more compact syntax, if you prefer a one-liner:

event (:freeze, {transitions_to: :frozen}) { my_freeze }