또는 오히려 어떻게 완벽하게 수행 할 수 있습니까?Ruby에서 아직 선언되지 않은 클래스를 게으른 평가 방법은 무엇입니까?
inst = Foo.new
inst.is_a? Foo # true, of course
inst.is_a? foo # TypeError: class or module required
이유 :
foo = Double(:Foo) # Now we can safely pass around Foo without
# having initialised it.
foo.class # Uninitialised constant
# That's expected because Foo doesn't exist yet!
class Foo; end # So there, we shoo it into existence.
foo.class # Foo # foo indeed is Foo. The sleight of hand of works.
이 내가 일을 얻을 수없는 것입니다 :
# A double that stands in for a yet-to-be-defined class. Otherwise
# known as "lazy evaluation."
#
# Idea lifted from:
# http://github.com/soveran/ohm/
class Double < BasicObject
def initialize(name)
@name = name
end
def to_s
@name.to_s
end
alias_method :inspect, :to_s
def method_missing(mth, *args, &block)
@unwrapped ? super : @unwrapped = true
::Kernel.const_get(@name).send(mth, *args, &block)
ensure
@unwrapped = false
end; private :method_missing
end
이 작동 :
이
는 지금까지 해낸 것입니다 마지막 줄에 Foo를 두 배로 표시하지 않겠습니까?
네, 두 번 뒤에있는 클래스를 숨기는 아이디어가 작동하지 않는 순간이라고 생각합니다. 그냥 함께 사는 법을 배워야합니다. –