Skip to content

Instantly share code, notes, and snippets.

@rtoal
Created December 4, 2016 16:41
Show Gist options
  • Save rtoal/748f4cedae86b49d3280b3df3a49907c to your computer and use it in GitHub Desktop.
Save rtoal/748f4cedae86b49d3280b3df3a49907c to your computer and use it in GitHub Desktop.
A lightweight, very convenient function to dynamically create good enums in Ruby
# Makes an enum class whose instances are all constants with uppercase names,
# but whose case of string representations are customizable. For example,
# Color = make_enum_class('red', 'amber', 'green') returns the class Color
# with members Color::RED, Color::AMBER, and Color::GREEN. The to_s methods
# produce 'red', 'green', and 'blue', respectively. To get the instance
# from the string, use, for example, Color.from_string('blue'), which will
# return Color.BLUE.
def make_enum_class(*constants)
cap = ->(s){s.upcase.gsub(/ /, '_')}
cls = Class.new
constants.each do |name|
cls.const_set(cap[name], cls.new).define_singleton_method(:to_s) {name}
end
cls.define_singleton_method(:from_s) {|s| cls.const_get(cap[s]) rescue nil}
cls
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment