Announcing the "Finite State Ma-thing", a base class to make it easy to implement a state-machine-like jobber.
'Tis a simple class at the core, but a powerful abstraction. (Ruby is so good at that.)
See the documentation (with pretty picture!) at http://phrogz.net/RubyLibs/FiniteStateMathing/, which also has a link to the full source code, and includes an example.
I used this as a proof-of-concept for a half-assed XML parser (behold the horror! at http://phrogz.net/tmp/XML_FSM.png), that sort of acts like a SAX parser. I don't know much about Finite State Machines or their theory, but the beauty of the solutions that FiniteStateMathing allows is that you _mostly_ use state to figure out what to do, but also have all the power of instance variables and methods at your disposal to help you along.
Because I wanted to allow _any_ object as a state, and because I could not find a way to invoke a class-scoped block to be executed (with parameter) in the scope of the instance, I'm using the #define_method hack suggested by Pit Captain, made uglier by me because (for uniqueness) all the method names are based off of the #object_id of the state.
This class was mostly an educational exercise for me. Please help further my education: gimme a holla if you see inefficiencies, have suggestions for cleaner ways to implement existing code, or envision cool features or cleaner interfaces.
Enjoy!
ยทยทยท
--
"When I am working on a problem I never think about beauty. I only think about how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong."
- R. Buckminster Fuller