`ClassName.constants`在Rails应用中返回空数组 [英] `ClassName.constants` returning empty array in Rails app
问题描述
我正在使用Rails 3应用程序,并且在lib
文件夹中有一个类的层次结构,例如:
I'm working on a Rails 3 app, and I've got a hierarchy of classes in my lib
folder, e.g.:
lib
├── assets
├── tasks
│ └── import.rake
└── importer
├── base.rb
└── source
├── facebook.rb
├── google.rb
└── twitter.rb
我更新了config/application.rb
,以包括以下行:
I've updated config/application.rb
to include this line:
config.autoload_paths += %W(#{config.root}/lib)
然后在Importer::Base
内部,我有一个实例方法试图加载Provider
模块中的所有类,例如:
Then inside of Importer::Base
, I have an instance method that attempts to load all classes in the Provider
module, e.g.:
Importer::Source.constants.each do |class_name|
Importer::Source.const_get(class_name).process
end
lib/importer/base
中的三个类的类层次结构类似于:
The three classes in lib/importer/base
have a class hierarchy similar to:
module Importer
module Source
class Facebook
# ...
end
end
end
当我调用此方法时,Importer::Source.constants
最终返回一个空数组.如果直接按名称引用这些类,则这些类似乎已正确装入,但是在constants
调用中无法访问.我该如何解决?
When I call this method, Importer::Source.constants
ends up returning an empty array. The classes appear to be lazy-loaded properly if I reference them by name directly, but they are not accessible in the constants
call. How can I fix this?
推荐答案
使用@apneadiving的建议,我可以通过将以下行添加到我的base.rb
文件的开头来解决此问题:
Using @apneadiving's suggestion, I was able to fix this by adding this line to the beginning of my base.rb
file:
Dir[Rails.root.join('lib/importer/source/**/*.rb')].each(&method(:require))
这篇关于`ClassName.constants`在Rails应用中返回空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!