2015-04-02 64 views
1

我的嘗試看起來像這樣,具有繼承性的非主動記錄模型。 app/models/matching_method.rbRails 4中的非主動記錄模型結構

class MatchingMethod 
    attr_accessor :name 
end 

class LD < MatchingMethod 
end 

class Soundex < MatchingMethod 
end 

通過這個我可以受益於使用MatchingMethod.descendants。 這工作得很好。所以我試圖將每個課程移到自己的文件夾中。

models/ 
    - concern/ 
    + matching_method/ 
    - ld.rb 
    - soundex.rb 
    - matching_method.rb 

併爲每個類:

class MatchingMethod::LD < MatchingMethod 
end 

不過,這一次MatchingMethod.descendants找不到 繼承的類了。

有什麼建議嗎?或者我應該重新設計這種方法。謝謝!

回答

3

僅當您請求MatchingMethod::LD時,導軌加載ld.rb。它通過const_missing解決了課程。您需要在代碼中請求MatchingMethod::LD或手動請求文件matching_method/ld.rb。直到類文件被加載,MatchingMethod不知道任何關於它的後代LD:再次

Dir['app/models/matching_method/*.rb'].each do |f| 
    require Pathname.new(f).realpath 
end 

要重新加載,無需重新啓動應用程序(如:

MatchingMethod.descendants 
# => [] 

MatchingMethod::LD   
# => MatchingMethod::LD 

MatchingMethod.descendants 
# => [MatchingMethod::LD] 

要加載的所有類從matching_method目錄在開發環境中的Rails裝載機):

Dir['app/models/matching_method/*.rb'].each do |f| 
    load Pathname.new(f).realpath 
end 

它將不是M監控文件更改。保存更改後,您需要手動輸入load文件。它不會刪除任何現有的方法/變量。它只會添加新的或改變現有的。

+0

謝謝!有沒有辦法自動加載這些後代方法? – 2015-04-02 15:09:06

+0

@PhatWangrungarun yes,Dir ['app/models/matching_method/*。rb']。each {| f | 需要Pathname.new(f).realpath} – 2015-04-02 15:12:30

+0

這很好,謝謝!但是,每次我在後代類中進行一些更改時,我都需要重新啓動應用程序才能獲得更改。這是正常的嗎? – 2015-04-02 17:21:06