Ruby: How to include namespaced classes into global namespace in IRB

放肆的年华 提交于 2019-12-13 13:25:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!