Ruby中的私有模块方法 [英] Private module methods in Ruby
本文介绍了Ruby中的私有模块方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个两部分的问题
最佳实践
- 我有一种算法,可以使用公共接口对数据结构执行某些操作
- 当前它是一个具有许多静态方法的模块,除了一个公共方法外,所有方法都是私有的接口方法。
- 所有方法之间都需要共享一个实例变量。
这些是我能看到的最好的选项:
These are the options I can see, which is the best?:
- Module with static('
- Class
- Mixin 包含模块进入数据结构
- 重构,将算法的一部分修改为该数据结构(非常小),并使之成为可调用该静态结构的静态方法的混合算法模块
具有静态方法的类
- Module with static ('module' in ruby) methods
- Class with static methods
- Mixin module for inclusion into the data structure
- Refactor out the part of the algorithm that modifies that data structure (very small) and make that a mixin that calls the static methods of the algorithm module
技术部分
有没有办法制作私有模块方法?
module Thing
def self.pub; puts "Public method"; end
private
def self.priv; puts "Private method"; end
end
私有
似乎没有任何作用,我仍然可以正常调用 Thing.priv
。
推荐答案
我认为最好的方法(主要是如何编写现有的lib)是通过在模块中创建一个处理所有逻辑的类,并且模块只是提供了一种方便的方法,例如
I think the best way (and mostly how existing libs are written) to do this is by creating a class within the module that deals with all the logic, and the module just provides a convenient method, e.g.
module GTranslate
class Translator
def perform( text ); translate( text ); end
private
def translate( text )
# do some private stuff here
end
end
def self.translate( text )
t = Translator.new
t.perform( text )
end
end
这篇关于Ruby中的私有模块方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文