Module: SimpleStates

Defined in:
lib/simple_states.rb,
lib/simple_states/event.rb,
lib/simple_states/states.rb,
lib/simple_states/version.rb

Defined Under Namespace

Modules: ClassMethods Classes: Event, States, TransitionException

Constant Summary collapse

VERSION =
'1.0.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



74
75
76
# File 'lib/simple_states.rb', line 74

def method_missing(method, *args, &block)
  method.to_s =~ /(was_|^)(#{self.class.states.join('|')})\?$/ ? send(:"#{$1}state?", $2, *args) : super
end

Instance Attribute Details

#past_statesObject (readonly)

Returns the value of attribute past_states.



52
53
54
# File 'lib/simple_states.rb', line 52

def past_states
  @past_states
end

Class Method Details

.included(base) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/simple_states.rb', line 9

def self.included(base)
  base.extend SimpleStates::ClassMethods
  # Add class level attribute accessors
  added_class_accessors = [ :state_names, :initial_state, :events ]
  base.singleton_class.send :attr_accessor, *added_class_accessors
  base.public_class_method *added_class_accessors
  base.public_class_method *added_class_accessors.map{|att| "#{att}=".to_sym }
  # default states
  base.after_initialize :init_state if base.respond_to?(:after_initialize)
  base.initial_state = :created
  base.events = []
end

Instance Method Details

#init_stateObject



54
55
56
# File 'lib/simple_states.rb', line 54

def init_state
  self.state = self.class.initial_state if state.nil?
end

#respond_to?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/simple_states.rb', line 70

def respond_to?(method, include_private = false)
  method.to_s =~ /(was_|^)(#{self.class.states.join('|')})\?$/ && self.class.state_names.include?($2.to_sym) || super
end

#state?(state, include_past = false) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/simple_states.rb', line 62

def state?(state, include_past = false)
  include_past ? was_state?(state) : self.state.try(:to_sym) == state.to_sym
end

#was_state?(state) ⇒ Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/simple_states.rb', line 66

def was_state?(state)
  past_states.concat([self.state.try(:to_sym)]).compact.include?(state.to_sym)
end