This is going to heavily quote https://www.rubyfleebie.com/enumerations-and-ruby/, please read that first. The proposed implementation lets you iterate over enumerated values, which is quite awesome. But it offers little in terms of reuse. Let’s improve upon it and split the methods in a way that lets us include an Enum implementation with all its class methods along the way. Full Enum.rb at the end.
The trick here is that when a class includes a module the module self.included method is invoked. The base parameter is the class object for the class that includes the module, so we can extend it with the _ClassMethods _implementation. Magical.
To define an order state enumeration we can now write the following.
You can call
I want to be able to write
define :CREATED = "CREATED" inside
OrderState class and I want to prevent instances of
OrderState outside of within
Enum. First one to accomplish both gets a beer.
Check out the ruby-enum gem.
The ruby-enum gem is used by 1M+ projects 🙈🙉.