Created
October 18, 2012 21:51
-
-
Save leonelgalan/3914981 to your computer and use it in GitHub Desktop.
A gem I plan to write
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(base) | |
#TODO: learn difference between extend and include (send :include, ) | |
base.extend ClassMethods | |
super | |
end | |
module ClassMethods | |
def enum(args) | |
# Constants | |
args.each do |name, array| | |
fields = array.collect do |key, value| | |
"['#{key.to_s}', #{key.to_s.upcase} = '#{value}']" | |
end.join(', ') | |
_module.module_eval "#{name.to_s.upcase} = [#{fields}]" | |
end | |
# Etc... | |
end | |
#TODO: better understand this | |
def _module | |
@_module ||= begin | |
mod = Module.new do | |
@_class_methods = Module.new | |
class << self | |
attr_reader :_class_methods | |
end | |
end | |
include mod | |
extend mod._class_methods | |
mod | |
end | |
end | |
end | |
end | |
class Test | |
include Enum | |
enum numbers: {one: 'Uno', two: 'Dos', three: 'Tres'} | |
# defines NUMBERS = [['one', ONE = 'Uno'], ['two', TWO = 'Dos'], ['three', THREE = 'Tres']] | |
def initialize | |
puts ONE | |
puts TWO | |
puts THREE | |
end | |
end | |
Test.new | |
# Uno | |
# Dos | |
# Tres |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment