2014-04-11 3 views
1
내가 루비 역 위임을 할 노력하고있어

, 나는 두 개의 클래스가 있다고 가정 해 Foo의 매크로 메소드 BarFoogreeting 메소드를 사용 하시겠습니까? 다음과 같이역 대표

+0

* 매크로 * 방법이란? –

+0

그런 꼬인 디자인입니다. ('@ bar') 객체의 [ "eigenclass"메소드] (http://timnew.github.io/blog/2012/05/25/open-eigenclass-in-ruby)를 무시할 수 있습니다. /), 그러나 * ick *. 이 순환 설계를 피하는 것이 일반적으로 더 좋습니다. ('Foo'의 인스턴스를'Bar' 초기화 메소드에 넘김으로써이를 해결할 때 더 명확한 순환 적 디자인 예제가 나타날 수 있습니다.) – user2864740

+0

Kinda가 목적에 맞습니다. 최종 목표는 메서드 호출을 통해 이벤트를 내보내는 sexp 파서 클래스를 "패치"하고이를 해당 클래스에 매핑하여 사용자 정의 클래스로 래핑 할 수 있도록하는 것입니다. – changelog

답변

1

당신은 class Bar을 변경할 수 있습니다 :

class Bar 
    def say_hello 
    puts greeting 
    end 

    def use_foos_greeting 
    self.class.class_eval do 
     def greeting 
     @f ||= Foo.new 
     @f.greeting 
     end 
    end 
    end 

    def use_bars_greeting 
    self.class.class_eval do 
     alias_method :greeting, :greeting_copy 
    end 
    end 

    def greeting 
    "Hello!" 
    end 

    alias_method :greeting_copy, :greeting 
end 

bar = Bar.new 
bar.greeting   #=> "Hello!" 
bar.use_foos_greeting 
bar.greeting   #=> "OHAI" 
bar.use_bars_greeting 
bar.greeting   #=> "Hello!" 

이 방법 고려 : 여기

@f ||= Foo.new 

def use_foos_greeting 
    self.class.class_eval do 
    def greeting 
     @f ||= Foo.new 
     @f.greeting 
    end 
    end 
end 

@f = @f || Foo.new 
대한 속기

처음으로 use_foos_greeting이 호출되면 @f => nil이므로 @fFoo.new으로 설정됩니다. use_foos_greeting으로 전화를 걸 때 @ftrue이므로 변경되지 않습니다. 이 메서드는 대신 @f = Foo.new이 있으면 작동하지만 메서드가 호출 될 때마다 Foo의 새 인스턴스가 만들어집니다 (이 인스턴스를 대체하면 가비지 수집 될 Foo의 인스턴스).

주 당신은 추가 할 수 없습니다 :

def initialize 
    @f = Foo.new 
end 

class Bar에이 Foo 인스턴스를 저장하려면, 클래스 Foo이 무한 루프가 발생할 것

def initialize 
    @f = Bar.new 
end 

을 가지고 있기 때문에.