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.



97
98
99
# File 'lib/simple_state/builder.rb', line 97

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.



107
108
109
# File 'lib/simple_state/builder.rb', line 107

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.



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/simple_state/builder.rb', line 117

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 event_permitted?(:process)
    #     _change_state_using_event!(:process)
    #   else
    #     false
    #   end
    # end
    @module.class_eval <<-RUBY, __FILE__, __LINE__ + 1
      def #{event}!
        if event_permitted?(:#{event})
          _change_state_using_event!(:#{event})
        else
          false
        end
      end
    RUBY
  end
end