Skip to content

Instantly share code, notes, and snippets.

@icebreaker
Last active August 29, 2015 13:58
Show Gist options
  • Save icebreaker/ea6958c675a730b6579d to your computer and use it in GitHub Desktop.
Save icebreaker/ea6958c675a730b6579d to your computer and use it in GitHub Desktop.
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