2011-09-12 5 views
1

또는 오히려 어떻게 완벽하게 수행 할 수 있습니까?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를 두 배로 표시하지 않겠습니까?

답변

4

코드에 아무 문제가 없습니다. 예상되는 동작입니다. #is_a? 메소드는 클래스 또는 모듈을 기대합니다. 빌드 클래스로 시도하면 같은 오류가 발생합니다.

str = "a string" 
str.is_a? String 
=> true 

other_str = "another string" 
str.is_a? other_str 
=> TypeError: class or module required 

변경하려면 is_a를 재정의해야합니까? (추천하지 않을 것이다). 더 많은 가능성이 같은 것을하고 싶지 :

str.is_a? other_str.class 
=> true 
+0

네, 두 번 뒤에있는 클래스를 숨기는 아이디어가 작동하지 않는 순간이라고 생각합니다. 그냥 함께 사는 법을 배워야합니다. –

0

당신이 foo 클래스 Foo 싶은 경우 : 당신이 행동을 정의 된 경우 대신 모듈에서 클래스에서 원하는 무엇

foo = Foo 
inst = Foo.new 
inst.is_a? foo #=> true 

inst2 = foo.new 
inst2.is_a? Foo #=> true 
0

에게 ?

아니면 모듈을 클래스로 감싸고 있을까요?

관련 문제