Rails 프로젝트에서 데코레이터를 사용하려고합니다.이 클래스 상속으로 인해 무한 재귀가 발생하는 이유
기본적으로 누락 된 메소드를 자원 객체 (또는 자원 객체의 클래스)에 위임하려고합니다.
여기서 클래스는 무한 순환 클래스 (단일)에서 일어나는 방법 self.method_missing
Decorator
그러나 단순화 된 예를
# 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
메서드를 구현할 필요가 없습니다.
응, 오타. 좋은 눈. –