Created
February 14, 2012 22:31
-
-
Save hopsoft/1831092 to your computer and use it in GitHub Desktop.
Example of a Ruby enum
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
module Enum | |
def self.included(mod) | |
mod.extend(ClassMethods) | |
end | |
module ClassMethods | |
def enum(*args) | |
raise "Enum already defined!" if @enum_hash | |
@enum_hash = {} | |
if args.length == 1 | |
args.first.each { |k, v| init_enum(k, v) } | |
else | |
args.each_with_index { |k, v| init_enum(k, v) } | |
end | |
@enum_hash.freeze | |
end | |
def enum_keys | |
@enum_hash.keys | |
end | |
def enum_values | |
@enum_hash.values | |
end | |
private | |
def init_enum(key, value) | |
key = prep_enum_key(key) | |
value.freeze | |
@enum_hash[key] = value | |
instance_variable_set("@#{key}".to_sym, value) | |
eigen.send(:attr_reader, key) | |
end | |
def prep_enum_key(key) | |
key.to_s.downcase.gsub(/\W/, "_").to_sym | |
end | |
def eigen | |
@eigen ||= class << self; self; end | |
end | |
end | |
end | |
# Example -------------------------- | |
module Colors | |
include Enum | |
enum :red, :blue, :green | |
end | |
Colors.red # => 1 | |
Colors.blue # => 2 | |
Colors.green # => 3 | |
module Colors | |
enum :orange, :violet, :aqua # => RuntimeError: Enum already defined! | |
end | |
module Shapes | |
include Enum | |
enum :circle => 0, | |
:triangle => 3, | |
:square => 4 | |
end | |
Shapes.circle # => 0 | |
Shapes.triangle # => 3 | |
Shapes.square # => 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment