Enum
This gem is an attempt to provide a lightweight (< 300 LOC, no dependencies) solution for object-oriented enumerations in Ruby. Ruby does not provide out of the box an enumerated type and the typical way of handling enumerated values is by using lists of symbols or strings. Although this is fine for simple cases, in more involved scenarios it leaves to the programmer the burden to store, validate and associate meaning and behaviour to the possible values.
Other languages, such as Java, have native support for enum types, providing a way of encapsulating the meaning and behaviour of the values in an object-oriented way.
This library attempts to bring a similar functionality to Ruby. It consists of a single class (Enum
), that can be subclassed to create enumerated types. Each class has a set of predefined instances, that represent the enumerated values.
A few similar gems have been built before, inspired by a similar design, but they missed features like support for inheritance and declaring instance methods on enumerated values, so this gem attempts to bridge that gap.
Installation
Add this line to your application's Gemfile:
gem 'enum_class'
And then execute:
$ bundle
Or install it yourself as:
$ gem install enum_class
Usage
Basic usage
class Weekday < Enum
value :MONDAY
value :TUESDAY
value :WEDNESDAY
value :THURSDAY
value :FRIDAY
value :SATURDAY
value :SUNDAY
end
Weekday.inspect # => Weekday(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, ...)
# Instances are accessible as constants or as class methods
Weekday::MONDAY.class # => Weekday
Weekday::TUESDAY.class # => Weekday
Weekday.monday # => Weekday::MONDAY
Weekday.tuesday # => Weekday::TUESDAY
Weekday::FOO # => raises NameError
Weekday.foo # => raises NameError
# Enumerated values are implicitly ordered, depending on order of definition
Weekday::MONDAY == Weekday::TUESDAY # => false
Weekday::MONDAY < Weekday::TUESDAY # => true
# Instances can be retrieved by key; keys are case-insensitive
Weekday[:monday] # => Weekday::MONDAY
Weekday['monday'] # => Weekday::MONDAY
Weekday.for('Monday') # => Weekday::MONDAY
Weekday.for('X') # => raises KeyError
Weekday.new # => raises an error
# Inspection methods
Weekday::MONDAY.monday? # => true
Weekday::TUESDAY.monday? # => false
# Enum classes implement all methods of Enumerable
Weekday.map { |weekday| "#{weekday.key}!" } # => ['MONDAY!', 'TUESDAY!', 'WEDNESDAY!', ...]
Creating enums with a shortcut
Grade = Enum.create(:a, :b, :c, :d, :e, :f) # => Grade(A, B, C, D, E, F)
Custom initializer and instance methods
class Color < Enum
def initialize(css_code)
@css_code = css_code
end
attr_reader :css_code
value :RED, '#ff0000'
value :GREEN, '#00ff00'
value :BLUE, '#0000ff'
end
Color::RED.css_code # => '#ff0000'
Color::GREEN.css_code # => '#00ff00'
Inheritance
class Base < Enum
value :A
value :B
end
class Child < Base
value :C
end
Base.inspect # => Base(A, B)
Child.inspect # => Child(A, B, C)
:warning: If you reopen the base class later, the changes won't be reflected in the child. The values to inherit are evaluated at the time of the class definition.
Advanced inheritance with custom initializer
class Base < Enum
def initialize(name)
@name = name
end
attr_reader :name
value :A, 'foo'
value :B, 'bar'
end
class Child < Base
def initialize(name, number)
super(name)
@number = number
end
def initialize_from_superclass(superclass_enum_value)
super # default behavior is to copy all the instance variables
@number = superclass_enum_value.ord + 1
end
attr_reader :number
value :C, 'baz', 3
end
Child::C.name # => 'baz'
Child::C.number # => 3
Child::B.name # => 'bar'
Child::B.number # => 2
Development
After checking out the repo, run bin/setup
to install dependencies. Then, run rake spec
to run the tests. You can also run bin/console
for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install
. To release a new version, update the version number in version.rb
, and then run bundle exec rake release
, which will create a git tag for the version, push git commits and tags, and push the .gem
file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/LIQIDTechnology/enum_class. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
License
The gem is available as open source under the terms of the MIT License.