Ruby:如何在IRB中将命名空间类包含到全局命名空间中 [英] Ruby: How to include namespaced classes into global namespace in IRB

查看:89
本文介绍了Ruby:如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆