【问题标题】:Ruby: How to include namespaced classes into global namespace in IRBRuby:如何将命名空间类包含到 IRB 的全局命名空间中
【发布时间】:2014-06-24 13:54:05
【问题描述】:

出于某种原因,我想使用命名空间的类/模块,因为它们位于 IRB 的全局命名空间中。

例如,我有模块MyCore 和类MyUser 里面。 IRB 是否有任何机制或钩子可以包含MyCore::MyUser,我可以只调用MyUser.new 而无需在其前面加上MyCore

【问题讨论】:

  • 你总是可以做MyUser = MyCore::MyUser

标签: ruby module namespaces irb


【解决方案1】:

你可以这样做

include MyCore

myUser = MyUser.new

使用include 将模块中的所有常量添加到您当前的类中。

class WhereIWantToIncludeMyCore
  include MyCore

  def initialize
    user = MyUser.new
  end
end

如果您希望能够在任何地方做到这一点,您可以将其添加到class 的范围之外,这会将其包含在Object 中。

【讨论】:

  • 假设 MyCore 是一个模块,您只能这样做
  • OP: "例如我有模块MyCore..."
【解决方案2】:

你可以做类似的事情

MU = MyCore::MyUser

并使用您为后续调用定义的别名。

【讨论】:

    【解决方案3】:

    你总是可以做到的

    MyUser = MyCore::MyUser
    

    如果你想获取所有包含的模块/类:

    MyCore.constants.each do |const|
      Object.const_set(const, MyCore.const_get(const))
    end
    

    【讨论】:

    • 哦,遍历所有常量,太棒了!
    【解决方案4】:

    我研究了这个问题,我发现了这个talking & scripts

    但我认为这颗宝石wrap_in_module 做得最好

    wrap_in_module

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 2019-11-15
      • 2011-08-29
      • 2010-11-21
      相关资源
      最近更新 更多