Skip to content

Instantly share code, notes, and snippets.

@leonelgalan
Created October 18, 2012 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonelgalan/3914981 to your computer and use it in GitHub Desktop.
Save leonelgalan/3914981 to your computer and use it in GitHub Desktop.
A gem I plan to write
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