Class: SimpleState::Builder::StateBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_state/builder.rb

Overview

Responsible for building events for a given state.

Instance Method Summary collapse

Constructor Details

#initialize(klass, mod, state) ⇒ StateBuilder

Returns a new instance of StateBuilder.



77
78
79
# File 'lib/simple_state/builder.rb', line 77

def initialize(klass, mod, state)
  @klass, @module, @state = klass, mod, state
end

Instance Method Details

#build(&blk) ⇒ Object

Specialises a state by defining events.

Parameters:

  • &blk (Block)

    An block for defining transitions for the state.



87
88
89
# File 'lib/simple_state/builder.rb', line 87

def build(&blk)
  instance_eval(&blk)
end

#event(event, opts = {}) ⇒ Object

Defines an event and transition.

Parameters:

  • event_name (Symbol)

    A name for this event.

  • opts (Hash) (defaults to: {})

    An options hash for customising the event.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/simple_state/builder.rb', line 97

def event(event, opts = {})
  unless opts[:transitions_to].kind_of?(Symbol)
    raise ArgumentError, 'You must declare a :transitions_to state ' \
                         'when defining events'
  end

  # Keep track of valid transitions for this state.
  @klass.states[@state].push([event, opts[:transitions_to]])

  unless @module.method_defined?(:"#{event}!")
    # Example:
    #
    # def process!
    #   if self.class._valid_transition?(self.state, :process)
    #     self.state =
    #       self.class._determine_new_state(self.state, :process)
    #   else
    #     false
    #   end
    # end
    @module.class_eval <<-RUBY, __FILE__, __LINE__ + 1
      def #{event}!
        if self.class._valid_transition?(self.state, :#{event})
          self.state =
            self.class._determine_new_state(self.state, :#{event})
        else
          false
        end
      end
    RUBY
  end
end