在 ruby 中,我如何知道哪个模块被定义为“load”的结果? 或“需要”?
在 ruby 中,如果我“require foo”,有没有办法随后确定 foo.rb 中定义的一个或多个模块的名称?
例如,假设我有一个名为 foo.rb 的 ruby 文件,如下所示:
# foo.rb
module MyModule
def self.summary
"this does something useful"
end
...
end
在另一个脚本中,在我执行“require foo”之后,如何确定我现在有一个名为 MyModule 的模块?
我最终想要的是能够做这样的事情:
file = someComputedFileName()
require file
puts "summary of #{file}: #{???::summary}
虽然我可以强迫自己使模块名称和文件名相同,但我宁愿不这样做。 我想要更自由地制作短文件名但更具表现力的模块名称。 但是,我向自己保证每个文件只会定义一个模块(想想:插件)。
In ruby, if I do "require foo", is there a way to subsequently determine the name of the module or modules defined in foo.rb?
For example, say I have a ruby file named foo.rb that looks like this:
# foo.rb
module MyModule
def self.summary
"this does something useful"
end
...
end
In another script, after I do "require foo", how can I determine that I now have a module named MyModule?
Ultimate what I'm after is to be able to do something like this:
file = someComputedFileName()
require file
puts "summary of #{file}: #{???::summary}
While I could force myself to make module names and file names identical, I'd rather not. I want a bit more freedom in making short filenames but more expressive module names. However, I am guaranteeing to myself that each file will only define a single module (think: plugins).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道这是否是最好的解决方案,但从我的角度来看,这似乎可行:
foo_constants 应该只为您提供由 foo.rb 定义的模块、类或其他常量。
I don't know if this is the best solution, but off the top of my head this seems to work:
foo_constants should give you only the modules, classes or other constants that were defined by foo.rb.
一种方法是使用 ObjectSpace.each_object(Module) 来查找在需要该文件之前定义的所有模块。 然后,在需要该文件后,再次循环所有定义的模块,看看是否有新的模块。
这还可以让您在文件中定义多个模块。
One approach would be to use ObjectSpace.each_object(Module) to find all defined modules before requiring the file. Then, after you require the file, loop over all defined modules again and see if there are any new ones.
That would also let you define more than one module in the file.