
This file only scratches the surface of AlterEgo functionality. The AlterEgo library provides both an object model for manually setting up explicit state classes, and a concise DSL built on top of that model which simplifies building classes with state-based behavior. Or in certain states some methods may not be supported at all. In this way, the implementation of those methods can vary with the state of the object. The object with state-based behavior delegates certain method calls to its current state. At any given time an object with state-based behavior has-a state object. In the State Pattern, states of an object are represented as discrete objects. Because AlterEgo uses the terminology set forth in the State Pattern, it is useful to have some familiarity with the pattern in order to understand the library. A summary of the pattern can be found on Wikipedia. In other words, it provides state-based polymorphism.ĪlterEgo draws heavily on the State Pattern as published in the book Design Patterns.

Storing and reading current state is completely customizable, making it easier to add AlterEgo to legacy classes.ĪlterEgo differs from other Finite State Machine implementations in Ruby in that where other libraries focus on describing a set of valid state transitions, AlterEgo focuses on varying behavior based on state.

Pervasive contract-checking catches mistakes in library usage early.

Uses dynamic module generation and delegation instead of method rewriting. Guard clauses may be defined for each transition.Įnter/exit actions may be defined for each state.įor more advanced scenarios, arbitrary “request filters” may be defined with full control over which requests are filtered. Implemented as a module which can be included in any Ruby class. SYNOPSIS: ¶ ↑ class TrafficLight include AlterEgo state :proceed, :default => true do handle :color do "green" end transition :to => :caution, :on => :cycle! end state :caution do handle :color do "yellow" end transition :to => :stop, :on => :cycle! end state :stop do handle :color do "red" end transition :to => :proceed, :on => :cycle! end end light = TrafficLight.

In effect, it makes it easy to give an object different personalities depending on the state it is in. It differs from other Ruby state machine libraries in that it focuses on providing polymorphic behavior based on object state. AlterEgo is a Ruby implementation of the State pattern as described by the Gang of Four.
