2012-09-14 26 views
0

我試圖幹掉我的Rails應用程序中的一些代碼,該代碼允許在使用過濾器創建對象時設置唯一的ID。我有它在多個位置,它似乎應該在一個模塊中,而不是。如何在模塊中引用Rails中的類的實例?

現在我在每個模型中都有類似的東西。

def set_uid 
    self.uid = SecureRandom.uuid 
    end 

我已經包含在文件uid_generator.rb我的/ lib目錄中的新文件,其中包括在每個模型的模塊。

//model 
include UidGenerator 

module UidGenerator 
    def set_uid 
    self.uid = SecureRandom.uuid 
    end 
end 

在我的測試然而,這會產生

uninitialized constant MODELNAME::UidGenerator (NameError). 

回答

3

你只需要配置Rails應用程序自動加載路徑的錯誤。這可能是有幫助的。 Best way to load module/class from lib folder in Rails 3?

+0

現在我已經有了這個路徑:config.autoload_paths + =%W(#{config.root}/lib/modules /) – Paul

+1

如果你想把它放在lib/modules中,那麼你需要給你打電話模塊「Modules :: UidGenerator」用於自動加載工作。 – sunkencity

+0

謝謝,我發現這篇博文很有幫助:http://www.williambharding.com/blog/technology/rails-3-autoload-modules-and-classes-in-production/ – Paul

相關問題