我正在使用以下Rails 3模型动态创建模型:
# encoding: UTF-8
require_dependency 'read_only'
require_dependency 'readings_methods'
class Reading < ActiveRecord::Base
self.abstract_class = true
include ReadOnly
include ReadingsMethods
@@mutex = Mutex.new
@@children = {}
def self.with_table(t)
@@mutex.synchronize do
child = @@children[t]
if child.nil?
child = Class.new(self) do
self.table_name = t
end
@@children[t] = child
end
child
end
end
end
然而,调试显示,@@children
在每次页面加载时都会重置,从而使每个页面加载非常非常缓慢。我该如何防止这种情况?是什么导致了它?除非我记住孩子,否则Rails会进入无限循环,这让我相信每当我创建一个新模型或类似的东西时它至少会重新加载一些类。如何防止此行为?
答案 0 :(得分:1)
Rails在开发模式下为您重新加载代码,这样您每次进行更改时都不必重新启动rails服务器(在rails 3.2中它尝试仅重新加载已更改的代码)。
当重新加载一个类时,rails取消设置常量并加载一个新的副本,因此特别是新的一个将有一组新的类变量。
ActiveSupport::Dependencies.autoload_once_paths
和ActiveSupport::Dependencies.autoload_paths
控制以这种方式重新加载的内容。您应该能够将文件的(完整)路径添加到autoload_once_paths以防止重新加载一个文件(但是您必须重新启动rails,以便查看对其进行的任何更改)