2013-05-29 3 views
0

Rails 프로젝트에서 데코레이터를 사용하려고합니다.이 클래스 상속으로 인해 무한 재귀가 발생하는 이유

기본적으로 누락 된 메소드를 자원 객체 (또는 자원 객체의 클래스)에 위임하려고합니다.

여기서 클래스는 무한 순환 클래스 (단일)에서 일어나는 방법 self.method_missingDecorator 그러나 단순화 된 예를

# Decorator base class 
class Decorator 
    attr_accessor :resource 

    private 

    def method_missing(name, *args, &block) 
     self.resource.send(name, *args, &block) 
    end 

    # infinite recursion happens here 
    def self.method_missing(name, *args, &block) 
     self.resource.class.send(name, *args, &block) 
    end 

end 

# Decorator class that will be used 
class UserCreator < Decorator 
    attr_reader :user 
    def initialize(params) 
     @user = User.new(params[:user]) 
     self.resource = @user 
    end 

    def save 
     # do special stuff with user object 
     if @user.save 
      # perhaps do some more stuff after the save 
      true 
     else 
      # perhaps handle the error here 
      false 
     end 
    end 

end 

# A simple controller example 
class SomeController < ApplicationController 
    respond_to :json 

    def create 
     @user = UserCreator.new(params) 

     if @user.save 
      render :json => @user 
     else 
      render :json => @user.errors 
     end 
    end 
end 

예요. 해당 메서드에서 인수로 resource을 전달 중입니다.

나는 여기서 무슨 일이 벌어지는 지 제어 흐름을 감싸고있다. 방법 resource은 클래스를 통해 attr_accessor을 기반으로 존재하므로 서브 클래스 UserCreator에도이 방법이 있습니다. 따라서 resource이 누락 된 방법이라고 생각하는 이유는 확실하지 않습니다. Decorator 수퍼 클래스를 제거하고 을 UserCreator 클래스에 구현하면 모두 예상대로 작동합니다.

예상대로 작동하도록이 기본 클래스를 구현하는 데 도움이되므로 모든 장식 자에서 동일한 method_missing 메서드를 구현할 필요가 없습니다.

+0

응, 오타. 좋은 눈. –

답변

2

두 번째 method_missing은 클래스 메소드입니다. 따라서이 메서드 내에서 self은 인스턴스가 아니라 클래스를 참조합니다.

그러나이 메서드는 클래스가 아닌 인스턴스의 특성 인 self.resource에 액세스하려고 시도합니다. Decorator 클래스가 더 resource 속성이 없기 때문에

, method_missing 내가 무슨 일이 일어나고 있는지의 제어 흐름 주위에 내 머리를 정리하려고

... 다시 다시 호출 ... 다시 ...하고 여기에. 방법 리소스

그것은 인스턴스 클래스 자체 데코레이터 클래스 있지만에 존재 attr_accessor 통해베이스 데코 클래스에 존재한다.

그래서 UserCreator 하위 클래스에는이 메서드가 있습니다.

인스턴스에는 UserCreator 하위 클래스가 있지만 하위 클래스는 포함되지 않습니다.

+0

매우 잘 설명되어 있습니다. 고맙습니다. –

관련 문제