Skip to content

Instantly share code, notes, and snippets.

@dkharrat
Created May 7, 2012 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkharrat/2629759 to your computer and use it in GitHub Desktop.
Save dkharrat/2629759 to your computer and use it in GitHub Desktop.
Enumerations in ruby
# credit goes to http://stackoverflow.com/questions/265725/what-is-the-best-way-to-handle-constants-in-ruby-when-using-rails
class Enumeration
def self.def_enum(key,value)
@hash ||= Hash.new { |hash, key| raise NameError, "#{self.name}::#{key} is not defined" }
@hash[key] = value
end
def self.const_missing(key)
@hash[key]
end
def self.each
@hash.each {|key,value| yield(key,value)}
end
def self.hash
@hash
end
def self.values
@hash.values || []
end
def self.keys
@hash.keys || []
end
def self.[](key)
@hash[key]
end
end
class Color < Enumeration
self.def_enum(:RED, '#f00')
self.def_enum(:GREEN, '#0f0')
self.def_enum(:BLUE, '#00f')
end
Color::RED => '#f00'
Color::GREEN => '#0f0'
Color::BLUE => '#00f'
Color.keys => [:RED, :GREEN, :BLUE]
Color.values => ['#f00', '#0f0', '#00f']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment