[英]Private methods in Ruby
An example of Rails controller which defines a private method: Rails控制器的一个例子,它定义了一个私有方法:
class ApplicationController < ActionController::Base
private
def authorization_method
# do something
end
end
Then, it's being used in a subclass of ApplicationController
: 然后,它被用在
ApplicationController
的子类中:
class CustomerController < ApplicatioController
before_action :authorization_method
# controller actions
end
How is it possible that a private method is called from its subclass? 如何从其子类调用私有方法? What is the meaning of
private
in Ruby? private
in Ruby是什么意思?
What private
does in Ruby, unlike in other languages, is make so that methods can not be called with explicit receiver . 与其他语言不同,Ruby中的
private
功能是使得无法使用显式接收器调用方法。
Aka, you can't call some_variable.some_private_method
or even self.some_private_method
. Aka,你不能调用
some_variable.some_private_method
甚至是self.some_private_method
。
That is all. 就这些。 They are still inherited.
它们仍然是遗传的。 You can read more here .
你可以在这里阅读更多。
The subclass inherits all of the methods and attributes from the superclass, including it's private methods. 子类继承了超类中的所有方法和属性,包括它的私有方法。 You are, in fact, calling the private method belonging to the subclass.
实际上,您正在调用属于子类的私有方法。
What you couldn't do is call authorization_method from outside ApplicationController (or subclasses of Authorization controller. Try this in the console: 你不能做的是从ApplicationController外部调用authorization_method(或授权控制器的子类。在控制台中尝试这个:
> ApplicationController.new.authorization_method
# NoMethodError: protected method `authorization_method' called for #<ApplicationController:0x0000000bb65778>
As Daniel noted in his response private method "cannot be called with an explicit receiver". 正如丹尼尔在他的回答中指出的那样,私人方法“不能用明确的接收者来调用”。 In another words, you cannot call private method using "dot" notation.
换句话说,您不能使用“点”表示法调用私有方法。 This is different from Java where you can call
this.privateMethod()
. 这与Java不同,您可以在其中调用
this.privateMethod()
。 In Ruby self.private_method
fails, but you can call it as private_method
instead. 在Ruby中,
self.private_method
失败,但您可以将其称为private_method
。
But there is one more way to call private methods of any object, which Rails internally uses to call before/after actions. 但是还有一种方法可以调用任何对象的私有方法,Rails内部使用它来在操作之前/之后调用。
If you have an instance obj
with private private_method
, you can invoke the method by: 如果你有一个带私有
private_method
的实例obj
,你可以通过以下方式调用该方法:
obj.send :private_method
Reality is, there are no private methods in Ruby in a strict sense. 现实是,严格意义上的Ruby中没有私有方法。 Privacy is "just recommendation, not the rule".
隐私是“只是推荐,而不是规则”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.