enum 형을 만들었다.
메소드 included, const_missing 을 눈여겨볼 것.
module EnumType
@@enums = {}
def initialize const, value
@const = const
@value = value
end
def to_i
@value
end
def to_s
"#{self.class}::#{@const}"
end
def self.included base
class << base
def const_missing const
@@enums.include?(const) ? @@enums[const] : raise(const.to_s)
end
def [](value)
@@enums[value]
end
def enum array
array.each_with_index do |const, value|
@@enums[const] = new(const, value)
@@enums[value] = @@enums[const]
end
end
end
base.private_class_method :new
end
end
class GIRepositoryError
include EnumType
enum [:G_IREPOSITORY_ERROR_TYPELIB_NOT_FOUND,
:G_IREPOSITORY_ERROR_NAMESPACE_MISMATCH,
:G_IREPOSITORY_ERROR_NAMESPACE_VERSION_CONFLICT,
:G_IREPOSITORY_ERROR_LIBRARY_NOT_FOUND
]
end
p GIRepositoryError[1].object_id
p GIRepositoryError[:G_IREPOSITORY_ERROR_NAMESPACE_MISMATCH].object_id
p GIRepositoryError::G_IREPOSITORY_ERROR_TYPELIB_NOT_FOUND.class
p GIRepositoryError::G_IREPOSITORY_ERROR_TYPELIB_NOT_FOUND
p GIRepositoryError::G_IREPOSITORY_ERROR_NAMESPACE_MISMATCH.object_id
p GIRepositoryError::G_IREPOSITORY_ERROR_NAMESPACE_MISMATCH
A Sponsored Dragon-Slaying
http://mislav.uniqpath.com/poignant-guide/book/chapter-6.html#section3
Metaprogramming in Ruby
http://ruby-metaprogramming.rubylearning.com/
댓글 없음:
댓글 쓰기