Simple type safe enum in Ruby English Posting

module Kernel
  def enum(*syms)
    new_class = Class.new do
      def initialize(name)
        @name = name
      end
      def to_s
        "#{self.class.name}::#{@name}"
      end
    end
    syms.each { |type| new_class.const_set(type, new_class.new(type)) }
    new_class
  end

  def enum2(*syms)
    syms.each do |sym|
      e = Object.new
      e.instance_eval("
        def to_s
          \"#{self}::#{sym.to_s}\"
        end
      ")
      const_set(sym.to_s, e)
    end
  end
end

Above is two types of type safe(I believe :-) Enum.

First type is constant defining style. For example

InstrumentType = enum :GUITAR, :BANJO, :DOBRO

Second type is including style. For example,

module InstrumentType
  enum2 :GUITAR, :BANJO, :DOBRO
end

What do you think about above code? Which one is better?

트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://classpath.egloos.com/tb/4735461 [도움말]

덧글

덧글 입력 영역


구글애드센스