【发布时间】: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 用于命名空间。
【问题讨论】:
-
private和protected在课堂环境中工作得更好。模块不会以相同的方式继承,因此限制要严格得多。