Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Add a state_transitions(requirements = {}) method #9

Open
wants to merge 1 commit into from

2 participants

@Gurpartap

To access available transitions with 'from' state, 'to' state, both, or 'on' event.

# Assuming
  states :created, :started, :finished

  event :start,  :from => :created, :to => :started
  event :finish, :to => :finished, :after => :cleanup
# Example 1:
  self.state = :created
  state_transitions # Assumes :from => self.state

# Result:
  [{:event => :start, :from => :created, :to => :started}]
# Example 2:
  state_transitions(:from => :created, :to => :started)

# Result:
  [{:event => :start, :from => :created, :to => :started}]
# Example 3:
  state_transitions(:to => :finished)

# Result:
  [{:event => :finish, :from => [:created, :started], :to => :finished}]
# Example 4:
  state_transitions(:on => :finish)

# Result:
  [{:event => :finish, :from => [:created, :started], :to => :finished}]
# Example 5:
  state_transitions(:on => :finish, :from => :started)

# Result:
  [{:event => :finish, :from => [:started], :to => :finished}]

OK. I know the code in the pull isn't the smartest around but it works :p

@travisbot

This pull request passes (merged 8b423d0 into dee8f11).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on May 28, 2012
  1. @Gurpartap
This page is out of date. Refresh to see the latest.
Showing with 21 additions and 0 deletions.
  1. +21 −0 lib/simple_states.rb
View
21 lib/simple_states.rb
@@ -48,6 +48,7 @@ def event(name, options = {})
end
attr_reader :past_states
+ attr_accessor :state_transitions
def init_state
self.state = self.class.initial_state if state.nil?
@@ -57,6 +58,26 @@ def past_states
@past_states ||= []
end
+ def state_transitions(requirements = {})
+ on ||= requirements[:on]
+ from ||= requirements[:from]
+ to ||= requirements[:to]
+ events.map { |event| { :options => event.options, :name => event.name} }.select { |event|
+ if on.present?
+ event[:name].eql?(on.try(:to_sym))
+ elsif from.present? && to.present?
+ [*event[:options].from].include?(from.try(:to_sym)) && [*event[:options].to].include?(to.try(:to_sym))
+ elsif from.present?
+ [*event[:options].from].include?(from.try(:to_sym))
+ elsif to.present?
+ [*event[:options].to].include?(to.try(:to_sym))
+ else
+ from = self.state
+ [*event[:options].to].include?(from.try(:to_sym))
+ end
+ }.map { |event| { :event => event[:name], :from => from.present? ? from : event[:options].from, :to => to.present? ? to : event[:options].to } }
+ end
+
def state?(state, include_past = false)
include_past ? was_state?(state) : self.state.try(:to_sym) == state.to_sym
end
Something went wrong with that request. Please try again.