Created
July 12, 2012 18:44
-
-
Save johnnypez/3100073 to your computer and use it in GitHub Desktop.
Enum for 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
# example | |
# | |
# States = enum %w(Draft Approved Published Trashed) | |
# => States {Draft, Approved, Published, Trashed} | |
# | |
# States::Draft | |
# => 1 | |
# | |
# States::Approved | |
# => 2 | |
# | |
# States::Published | |
# => 4 | |
# | |
# States::Trashed | |
# => 8 | |
# | |
# States::Approved | States::Draft | |
# => 3 | |
# | |
# States::Approved | States::Published | |
# => 6 | |
module Enum | |
def enum(values) | |
Module.new do |mod| | |
values.each_with_index{ |v,i| mod.const_set(v.to_s.capitalize, 2**i) } | |
def mod.inspect | |
"#{self.name} {#{self.constants.join(', ')}}" | |
end | |
end | |
end | |
end | |
include Enum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment