【问题标题】:Private module method accessible by module classes模块类可访问的私有模块方法
【发布时间】:2017-11-07 03:10:18
【问题描述】:

我正在尝试使用 Ruby gem 包装命令行实用程序(我们称之为foo)的功能。我正在尝试将一些功能抽象到不同的类中,但我希望拥有处理以一种方法调用系统的逻辑,以便我可以在一个地方处理来自应用程序的错误。

我可以通过在 gem 的主模块中定义一个方法来轻松地做到这一点

module Foo
  def self.execute(*args)
    exec('foo', *args)
    # Pretend there is a lot more error handling etc. here
  end
end

然后每个类都可以通过此方法将调用传递给可执行文件

module Foo
  class Bar

    # Access via class method
    def self.list_bars
      Foo.execute('ls', 'bars')
    end

    # Access via instance method
    def initialize
      # Make a call to the system executable via the class method
      Foo.execute('initialize', 'bar')
    end

    def config(*args)
      Foo.execute('config', 'bar', *args)
    end
  end
end

不过,理想情况下,我想让Foo.execute 方法私有,这样我的模块的公共API 就完全是foo 的抽象。如果我将Foo.execute 标记为private,那么模块中的其他类(显然)无法访问它。

如何使用 Ruby 2.3 简洁地实现这一点?

还值得注意的是,我实际上仅将模块 Foo 用于命名空间。

【问题讨论】:

  • privateprotected 在课堂环境中工作得更好。模块不会以相同的方式继承,因此限制要严格得多。

标签: ruby oop rubygems


【解决方案1】:

ruby 中的模块只是方法和常量的容器。类对它们构成的模块一无所知并且不从它们继承。所以没有办法让 'Foo' 上的方法可用于其中可能包含的所有类。

这种方法可能会给你想要的。

module Foo
  module CommandRunning
    def execute(*args)
      # ...
    end
  end

  class Bar
    include CommandRunning

    def initialize
      execute('initialize', 'bar')
    end
  end
end

【讨论】:

  • 这很有帮助。我最终做了一些非常相似的事情。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多