Created
May 7, 2012 19:09
-
-
Save dkharrat/2629759 to your computer and use it in GitHub Desktop.
Enumerations in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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