당신은 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
이므로 @f
은 Foo.new
으로 설정됩니다. use_foos_greeting
으로 전화를 걸 때 @f
은 true
이므로 변경되지 않습니다. 이 메서드는 대신 @f = Foo.new
이 있으면 작동하지만 메서드가 호출 될 때마다 Foo
의 새 인스턴스가 만들어집니다 (이 인스턴스를 대체하면 가비지 수집 될 Foo
의 인스턴스).
주 당신은 추가 할 수 없습니다 :
def initialize
@f = Foo.new
end
class Bar
에이 Foo
인스턴스를 저장하려면, 클래스 Foo
이 무한 루프가 발생할 것
def initialize
@f = Bar.new
end
을 가지고 있기 때문에.
* 매크로 * 방법이란? –
그런 꼬인 디자인입니다. ('@ bar') 객체의 [ "eigenclass"메소드] (http://timnew.github.io/blog/2012/05/25/open-eigenclass-in-ruby)를 무시할 수 있습니다. /), 그러나 * ick *. 이 순환 설계를 피하는 것이 일반적으로 더 좋습니다. ('Foo'의 인스턴스를'Bar' 초기화 메소드에 넘김으로써이를 해결할 때 더 명확한 순환 적 디자인 예제가 나타날 수 있습니다.) – user2864740
Kinda가 목적에 맞습니다. 최종 목표는 메서드 호출을 통해 이벤트를 내보내는 sexp 파서 클래스를 "패치"하고이를 해당 클래스에 매핑하여 사용자 정의 클래스로 래핑 할 수 있도록하는 것입니다. – changelog