lib/abstractivator/enum.rb in abstractivator-0.0.27 vs lib/abstractivator/enum.rb in abstractivator-0.0.28
- old
+ new
@@ -8,11 +8,11 @@
# base.extend Dsl
end
module ClassMethods
def values
- self.constants.map{|sym| self.const_get(sym)}.reject{|x| x == Enum::ClassMethods}
+ self.constants.map{|sym| self.const_get(sym)}.reject{|x| x.is_a?(Class) || x.is_a?(Module)}
end
def name_for(value)
self.constants.detect{|sym| self.const_get(sym) == value}
end
@@ -20,11 +20,11 @@
def from_symbol(sym)
safe_constantize("#{self.name}::#{sym.to_s.upcase}")
end
def from(x)
- values.find{|v| v == x}
+ values.find{|v| v.value == x}
end
private
def safe_constantize(str)
@@ -35,27 +35,10 @@
end
end
end
end
-module EnumMember
- attr_accessor :enum_type
-end
-
-class Object
- include EnumMember
-end
-
-class WrappedEnumValue < SimpleDelegator
- include EnumMember
- attr_reader :class # pure evil
- def initialize(value)
- __setobj__(value)
- @class = value.class
- end
-end
-
def define_enum(name, *fields)
if respond_to?(:const_set)
const_set(name, make_enum(*fields))
else # top-level
Object.send(:const_set, name, make_enum(*fields))
@@ -65,12 +48,23 @@
def make_enum(*fields)
if fields.size == 1 && fields.first.is_a?(Hash) && fields.first.keys.all?{|f| f.is_a?(Symbol)}
fields = fields.first
Module.new do
include Enum
+ value_class =
+ const_set(:Value,
+ Class.new do
+ attr_reader :enum_type, :value
+ define_method(:initialize) do |enum_type, value|
+ @enum_type, @value = enum_type, value
+ end
+ define_method(:inspect) do
+ "#<#{self.class.name} #{value.inspect}>"
+ end
+ alias_method :to_s, :inspect
+ end)
fields.each_pair do |k, v|
- val = v.frozen? ? WrappedEnumValue.new(v) : v
- val.enum_type = self
+ val = value_class.new(self, v)
fld = k.to_s.upcase.to_sym
const_set(fld, val)
end
end
elsif fields.all?{|f| f.is_a?(Symbol)}