Module: SimpleStates

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

Defined Under Namespace

Modules: ClassMethods, Helpers Classes: Error, Event, States

Constant Summary collapse

VERSION =
'2.0.1'

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



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

def method_missing(name, *args)
  state = name.to_s[0..-2].to_sym
  return super unless name.to_s[-1] == '?' && self.class.state?(state)
  state?(state)
end

Class Method Details

.included(const) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/simple_states.rb', line 7

def included(const)
  states = const.const_set(:States, States.new)
  const.send(:prepend, states) if const.respond_to?(:prepend)
  const.extend(ClassMethods)
  const.initial_state = :created
  const.after_initialize(:init_state) if const.respond_to?(:after_initialize)
end

Instance Method Details

#init_stateObject



37
38
39
40
# File 'lib/simple_states.rb', line 37

def init_state
  singleton_class.send(:include, self.class::States) unless self.class.respond_to?(:prepend)
  self.state = self.class.initial_state if self.state.nil?
end

#reset_stateObject



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

def reset_state
  self.state = self.class.initial_state
  self.class::States.events.map { |_, event| event.reset(self) }
end

#respond_to?(name) ⇒ Boolean

Returns:

  • (Boolean)


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

def respond_to?(name)
  state = name.to_s[0..-2].to_sym
  name.to_s[-1] == '?' && self.class.state?(state) || super
end

#stateObject



46
47
48
49
# File 'lib/simple_states.rb', line 46

def state
  state = super
  state.to_sym if state
end

#state=(state) ⇒ Object



42
43
44
# File 'lib/simple_states.rb', line 42

def state=(state)
  super(state.to_sym)
end

#state?(state) ⇒ Boolean

Returns:

  • (Boolean)


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

def state?(state)
  self.state.to_sym == state.to_sym
end