ruby - 是否可以在 Ruby 中显式包含子模块或类?

标签 ruby

我希望能够静态分析我的代码。也就是说,从文件的纯文本中知道每个函数和变量来自哪里。当 IDE 和文本编辑器插件也可以追踪每个符号的来源时,它们的工作效果会更好。

例如,如果我有这样的应用程序代码:

#...
Y.some_method()
#...

然后我想在页面上某处的 include/import/require/extend/def 语句中看到 Y

在我使用的其他语言中,可以显式选择将命名空间的哪些子部分引入当前上下文。

Python:

from X import Y

haskell :

import X (Y)

Elixir :

alias X.Y, as: Y

虽然可以导入 Python 中所有包含的名称,但“通配符导入”is frowned upon :

from X import *

". . . they make it unclear which names are present in the namespace, confusing both readers and many automated tools."

在 Ruby 中,这种完全隐式的“通配符”方式似乎是引入包含名称的唯一方式:

include X

这使得 Y 可用,但是有什么方法可以使其明确吗? docs for Ruby include不显示任何选项。

我真正想在 Ruby 中做的事情是这样的:

from X include Y
include X::Y as Y

到目前为止我想到的最好的办法是:

require 'x/y' ; Y = X::Y

这是a crazy hack在另一个可以实现这一点的问题的答案中。

最佳答案

试试这个。但我同意 @tadman 的观点,即您应该考虑以 Ruby 方式进行操作。

Object.define_singleton_method(:include) do |*mths, from: nil|
  mod = from || mths.first
  mod = mod.dup

  if from
     all_mths = mod.instance_methods
     (all_mths - mths).each { |mth| mod.send :undef_method, mth }
  end

  super(mod)
end

module Foobar
  def foo
    puts :foo
  end

  def bar
    puts :bar
  end
end

class Abc
  include Foobar
end

Abc.new.foo # => 'foo'
Abc.new.bar # => 'foo'

class AbcWithoutBar
  include :foo, from: Foobar
end

AbcWithoutBar.new.foo # => 'foo'
AbcWithoutBar.new.bar # => NoMethodError

关于ruby - 是否可以在 Ruby 中显式包含子模块或类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646754/

相关文章:

mysql - 不同的 Rails 查询

ruby - 使用 Ruby 从文件夹中获取所有文件的名称

ruby-on-rails - SQLite3的助手?

ruby-on-rails - rvm --default 不设置 1.9.2 ubuntu 11.10 + 无法安装 rails

java - 在 SWT 应用程序中使用 styledText

css - 如何将链接分配给 omniauth facebook 按钮

ruby - 删除 Ruby 中的换行符

ruby - 如何使用 watir-webdriver 查找特定表

ruby - Redis 阻塞保存

ruby-on-rails - 反序列化的 Rails ActiveRecord 对象不会保存到 SQL 数据库