模块 类 可访问的私有模块方法
Private module method accessible by module classes
我正在尝试用 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
方法设为 private,以便我的模块的 public API仅仅是 foo
的抽象。如果我将 Foo.execute
标记为 private
,那么模块中的另一个 类(显然)无法访问它。
如何使用 Ruby 2.3 简洁地完成此操作?
同样值得注意的是,我实际上只是将模块 Foo
用于命名空间目的。
ruby 中的模块只是方法和常量的容器。 类 对它们构成的模块一无所知,也没有从它们继承。因此无法使“Foo”上的方法可用于其中可能包含的所有 类。
这种方法可能会满足您的需求。
module Foo
module CommandRunning
def execute(*args)
# ...
end
end
class Bar
include CommandRunning
def initialize
execute('initialize', 'bar')
end
end
end
我正在尝试用 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
方法设为 private,以便我的模块的 public API仅仅是 foo
的抽象。如果我将 Foo.execute
标记为 private
,那么模块中的另一个 类(显然)无法访问它。
如何使用 Ruby 2.3 简洁地完成此操作?
同样值得注意的是,我实际上只是将模块 Foo
用于命名空间目的。
ruby 中的模块只是方法和常量的容器。 类 对它们构成的模块一无所知,也没有从它们继承。因此无法使“Foo”上的方法可用于其中可能包含的所有 类。
这种方法可能会满足您的需求。
module Foo
module CommandRunning
def execute(*args)
# ...
end
end
class Bar
include CommandRunning
def initialize
execute('initialize', 'bar')
end
end
end