问题
For some reason I want to use namespaced Classes/Modules as they are in global namespace in IRB.
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
?
回答1:
You can simply do
include MyCore
myUser = MyUser.new
Using include
adds all the constants in the module to you current class.
class WhereIWantToIncludeMyCore
include MyCore
def initialize
user = MyUser.new
end
end
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
.
回答2:
You could do something like
MU = MyCore::MyUser
and use the alias you defined for subsequent calls.
回答3:
You can always do
MyUser = MyCore::MyUser
If you want to get all the included modules/classes:
MyCore.constants.each do |const|
Object.const_set(const, MyCore.const_get(const))
end
回答4:
i research about this problem and i found this talking & scripts
but i thought this gem wrap_in_module
does the best practise
wrap_in_module
hope it helps.
来源:https://stackoverflow.com/questions/23520321/ruby-how-to-include-namespaced-classes-into-global-namespace-in-irb