ruby - 文件私有方法 [英] ruby - File-private methods

查看:28
本文介绍了ruby - 文件私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ruby​​ 中,有没有办法定义一个方法,该方法对文件(或模块)中的每个类都可见,但对需要该文件的文件不可见?

In ruby, is there a way to define a method that is visible by every class in the file (or in the module), but not by files that require the file ?

相关,但不完全相同:我们是否可以重新定义一个方法(例如来自标准库类的方法),以便此重新定义仅在当前文件中可见?所有其他文件应查看原始定义.

Related, but not quite the same: can we redefine a method (for instance a method from a class of the standard library) such that this redefinition is visible only in the current file ? All other files should view the original definition.

推荐答案

No and no.

Ruby 中唯一的可见性是 public、protected 和 private.没有文件级可见性的概念.你也许可以欺骗"并做这样的事情:

The only visibilities in Ruby are public, protected, and private. There is no concept of file-level visibility. You could maybe "cheat" and and do something like this:

# In some file foobar.rb

class Foo
  def to_bar
    Bar.new.file_private
  end
end

class Bar
  def file_private
    raise unless caller[0].split(':')[0] == __FILE__
  end
end

# In IRB or some other file

Foo.new.to_bar  #=> nil
Bar.new.file_private  #=> RuntimeError

但这是个坏主意.不同目录中的同名文件可能有效.它也不是真正的可见性,而是在方法本身中强制执行它.

But this is a bad idea. A file of the same name in a different directory might work. It also isn't true visibility, but rather enforces it in the method itself.

不过,实际上,您应该将每个类都放在自己的文件中.它使组织更好.此外,您不应依赖公共/受保护/私有.你总是可以只使用 send 来调用私有方法,但上面的打破这种期望.如果您的代码的用户真的想用您的代码做某事,那么让他们做几乎没有什么,这就是动态语言的本质.如果您不记录方法,大多数用户甚至都不会知道它的存在:P.

Really, though, you should mostly have your classes each in their own file. It makes organization better. Further, you should not depend on public/protected/private. You can always just use send to call a private method, but the above breaks that expectation. If user of your code really wants to do something with your code, there's next to nothing from letting them do it, that's the nature of dynamic languages. If you don't document a method, most users will never even know it's there anyway :P.

关于你的第二个问题,在同一个类中不可能有两个同名的方法,但是可见性不同,第二个方法总是会覆盖原来的.你可以做一些类似于我上面所做的事情,并根据条件运行不同的代码而不是提高,但如上所述,我并不认为这是一个好主意.

As for your second question, there is no way to have two methods of the same name in the same class with different visibility, the second method will always overwrite the original. You could do something similar to what I've done above, and run different code depending on the condition instead of raising, but as above I don't really think this is a good idea.

这篇关于ruby - 文件私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆