Create a gist now

Instantly share code, notes, and snippets.

@icebreaker /nano_enum.rb Secret
Last active Aug 29, 2015

What would you like to do?
Nano Enum v3
module NanoEnum
class << self
def included(base)
base.extend(ClassMethods)
end
end
module ClassMethods
def enum(*members)
if members.first.is_a?(Hash)
member_values = members.first.values
iterator = members.first.each_pair
else
member_values = members.each_index.to_a
iterator = members.each_with_index
end
klass = Class.new(Integer)
klass.instance_eval <<-CODE, __FILE__, __LINE__ + 1
def include?(value)
#{member_values}.include?(value)
end
def to_a
#{member_values}
end
CODE
iterator.each do |member, value|
klass.const_set(member.to_s.upcase, value)
end
klass
end
end
end
if $0 == __FILE__
require 'mongoid'
class Model
include Mongoid::Document
include NanoEnum
TYPE = enum :apple => 15, :orange => 16
field :type, :type => TYPE, :default => TYPE::ORANGE
#field :type, :type => Integer, :default => TYPE::ORANGE
validates_inclusion_of :type, :in => TYPE
end
puts Model::TYPE.superclass.name
model = Model.new
puts model.valid?
puts model.inspect
model.type = Model::TYPE::APPLE
puts model.valid?
puts model.inspect
model.type = 13
puts model.valid?
puts model.inspect
puts model.errors.full_messages
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment