2015-01-16 5 views
0

내 레일 앱에서 다중 테이블 상속을 구현하기 위해 active_record-acts_as 보석을 사용하고 있습니다. 이 보석은 하위 클래스가 상위 클래스와 같이 작동하도록 도와 주므로 상위 클래스의 메서드에 응답합니다. 부모 클래스가 라우팅을 단순화하기 때문에 자식 클래스의 메서드에도 응답하도록 만들고 싶습니다. 이 위대한 작품을respond_to를 구현 하시겠습니까? method with active_record-acts_as gem

class ParentClass < ActiveRecord::Base 
    actable as: :assetable 

    def method_missing_with_specific(method, *args, &block) 
    # specific is the associated child class instance 
    if specific.respond_to?(method) 
     specific.send(method, *args, &block) 
    else 
     method_missing_without_specific(method, *args, &block) 
    end 
    end 

    alias_method_chain :method_missing, :specific 

    def is_a_with_specific?(type) 
    if assetable_type.constantize == type 
     true 
    else 
     is_a_without_specific?(type) 
    end 
    end 

    alias_method_chain :is_a?, :specific 
end 

,하지만 난 문제가 method_missing 하나 이동합니다 respond_to? 방법을 구현하는 데 문제가 있습니다 :

지금까지 내가 가지고있다.

내가 시도 :

def respond_to?(method, private=false) 
    super || specific.respond_to?(method, private) 
end 

과 :

분명히
Failure/Error: Unable to find matching line from backtrace 
SystemStackError: 
    stack level too deep 
# /Users/blueye/.rvm/gems/ruby-2.1.1/gems/activerecord-4.1.2/lib/active_record/transactions.rb:286 
# 
# Showing full backtrace because every line was filtered out. 
# See docs for RSpec::Configuration#backtrace_exclusion_patterns and 
# RSpec::Configuration#backtrace_inclusion_patterns for more information. 

내가 무한 재귀의 일종을 유발하고 이러한 방법 모두가 함께 실패 내 테스트 결과

def respond_to_with_specific?(method, private=false) 
    if specific.respond_to?(method, private) 
    true 
    else 
    respond_to_without_specific?(method, private) 
    end 
end 

alias_method_chain :respond_to?, :specific 

ActiveRecord와 상호 작용할 때, 그러나 나는 잘 모르겠다.

이 경우 respond_to?을 어떻게 구현할 수 있습니까?

는 업데이트 :

def respond_to?(name, include_private = false) 
    super || acting_as.respond_to?(name) 
end 

은 각 클래스가 다른 respond_to?을 위임 계속 순환 논리의 일종을 만드는 것처럼 보인다 :

나는 보석에 다음 코드를 발견했다. 자식 클래스에서이 메서드를 재정의하려고 시도했지만 super을 호출하면 gem 모듈에서 포함 된 메서드로 위임하는 것처럼 보입니다.

답변

1

귀하의 방법 내에서 respond_to? 메서드를 호출하므로 무한 재귀가 발생합니다.

def respond_to_with_specific?(method, private=false) 
    specific.respond_to_without_specific?(method, private) 
end 
+0

이 여전히 나에게 무한 루프를 줄 것으로 보인다 : 자식 클래스가 부모 클래스 플러스 몇 가지 방법의 모든 방법을해야하기 때문에

, 당신은 할 수 있어야한다. – ptd