2015-01-16 39 views
0

我正在使用active_record-acts_as gem在我的Rails應用程序中實現多表繼承。這個gem幫助一個孩子類像父類一樣行爲,所以它響應父類的方法。我想讓父類也響應子類的方法,因爲它簡化了路由。執行respond_to?方法與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 

這個偉大的工程,但我在實施的respond_to?方法去與method_missing一個麻煩。

我想:

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

和:

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 

這兩種方法都導致我的測試與失敗:

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. 

顯然我造成某種無限遞歸當與ActiveRecord互動時,但我不知道如何。

在這種情況下,我如何實現respond_to?

更新:

我發現,在創業板下面的代碼:

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

這似乎是它會建立某種形式的每個類保持委託respond_to?其他循環邏輯的。我嘗試在子類中重寫此方法,但調用super似乎只是將其委託給gem模塊中包含的方法。

回答

1

您在respond_to_with_specific?方法內呼叫respond_to?,因此無限遞歸。

由於子類應該有父母類一些方法的所有方法,你應該能夠只是做:

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

這似乎仍然給我一個無限循環。 – ptd