Created
May 20, 2011 15:00
-
-
Save rklemme/983088 to your computer and use it in GitHub Desktop.
Yet another 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
class Enum | |
module EnumMember | |
attr_reader :args | |
def [](idx) | |
args[idx] | |
end | |
end | |
class <<self | |
include Enumerable | |
def each(&b) | |
values.each(&b) | |
self | |
end | |
def values | |
constants.map {|c| const_get(c)} | |
end | |
def enum(*args) | |
cl = Class.new(self) | |
cl.instance_variable_set("@args", args.freeze) | |
cl.extend(EnumMember).freeze | |
end | |
def inherited(cl) | |
class <<cl | |
private :new, :allocate | |
end | |
end | |
end | |
end | |
class GenericState < Enum | |
ACCEPTED = enum "foo" | |
UNSURE = enum | |
end | |
p GenericState.values | |
GenericState.each {|s| p s} | |
p GenericState.map(&:name) | |
p GenericState::ACCEPTED[0] | |
GenericState.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment