diff --git a/README.adoc b/README.adoc index 96b35c1e6..be4c785e4 100644 --- a/README.adoc +++ b/README.adoc @@ -342,6 +342,8 @@ Advanced usage You can easily reflect on workflow specification programmatically - for the whole class or for the current object. Examples: +include::test/reflection_test.rb[tag=reflect] + article2.current_state.events # lists possible events from here article2.current_state.events[:reject].transitions_to # => :rejected @@ -375,18 +377,20 @@ representation of the workflow. See below. Conditions can be a "method name symbol" with a corresponding instance method, a `proc` or `lambda` which are added to events, like so: - state :off - event :turn_on, :transition_to => :on, - :if => :sufficient_battery_level? +.... +state :off + event :turn_on, :transition_to => :on, + :if => :sufficient_battery_level? - event :turn_on, :transition_to => :low_battery, - :if => proc { |device| device.battery_level > 0 } - end + event :turn_on, :transition_to => :low_battery, + :if => proc { |device| device.battery_level > 0 } +end - # corresponding instance method - def sufficient_battery_level? - battery_level > 10 - end +# corresponding instance method +def sufficient_battery_level? + battery_level > 10 +end +.... When calling a `device.can_?` check, or attempting a `device.!`, each event is checked in turn: diff --git a/test/reflection_test.rb b/test/reflection_test.rb new file mode 100644 index 000000000..9e1bdb642 --- /dev/null +++ b/test/reflection_test.rb @@ -0,0 +1,36 @@ +require File.join(File.dirname(__FILE__), 'test_helper') +require 'workflow' + +# Example from the README, TODO: integrate other way around via asciidoctor code inclusion +class Article + include Workflow + workflow do + state :new do + event :submit, :transitions_to => :awaiting_review + end + state :awaiting_review do + event :review, :transitions_to => :being_reviewed + end + state :being_reviewed do + event :accept, :transitions_to => :accepted + event :reject, :transitions_to => :rejected + end + state :accepted + state :rejected + end +end + +class MainTest < Minitest::Test + test 'reflection' do + article2 = Article.new + article2.submit! + article2.review! + assert_equal 2, article2.current_state.events.length + # Please note the usage of `first`, since coditional event transitions can + # define multiple event definitions with the same name + + # tag::reflect[] + assert_equal :rejected, article2.current_state.events[:reject].first.transitions_to + # end::reflect[] + end +end