Ruby:如何在IRB中将命名空间类包含到全局命名空间中 [英] Ruby: How to include namespaced classes into global namespace in IRB
问题描述
由于某种原因,我想使用命名空间的类/模块,因为它们位于IRB的全局命名空间中.
For some reason I want to use namespaced Classes/Modules as they are in global namespace in IRB.
例如,我内部有模块MyCore
和类MyUser
.是否有任何机制或挂钩可以让IRB包括MyCore::MyUser
,而我可以只调用MyUser.new
而不用MyCore
作为前缀?
For example I have module MyCore
and class MyUser
inside it. Is there any mechanism or hook for IRB to include MyCore::MyUser
in a way I can call just MyUser.new
without prefixing it with MyCore
?
推荐答案
您可以轻松完成
include MyCore
myUser = MyUser.new
使用include
将模块中的所有常量添加到您当前的类中.
Using include
adds all the constants in the module to you current class.
class WhereIWantToIncludeMyCore
include MyCore
def initialize
user = MyUser.new
end
end
如果您希望能够在任何地方执行 ,则可以将其添加到class
范围之外,该范围将包括在Object
中.
If you want to be able to do that everywhere, you can add it outside the scope of a class
, which will include it to Object
.
这篇关于Ruby:如何在IRB中将命名空间类包含到全局命名空间中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!