有没有办法从 Ruby 中的实例调用私有类方法?
-
09-06-2019 - |
题
以外 self.class.send :method, args...
, , 当然。我想在类和实例级别提供一个相当复杂的方法,而无需重复代码。
更新:
@乔纳森·布拉南:这是我的假设,但我想确保没有其他人找到解决方法。Ruby 中的可见性与 Java 中的可见性有很大不同。你也说得很对 private
不适用于类方法,尽管这将声明一个私有类方法:
class Foo
class <<self
private
def bar
puts 'bar'
end
end
end
Foo.bar
# => NoMethodError: private method 'bar' called for Foo:Class
解决方案
这是与问题相关的代码片段。在类定义中使用“private”不适用于类方法。您需要使用“private_class_method”,如下例所示。
class Foo
def self.private_bar
# Complex logic goes here
puts "hi"
end
private_class_method :private_bar
class <<self
private
def another_private_bar
puts "bar"
end
end
public
def instance_bar
self.class.private_bar
end
def instance_bar2
self.class.another_private_bar
end
end
f=Foo.new
f=instance_bar # NoMethodError: private method `private_bar' called for Foo:Class
f=instance_bar2 # NoMethodError: private method `another_private_bar' called for Foo:Class
我看不出有什么办法可以解决这个问题。文档说你不能指定私有方法的接收。此外,您只能从同一实例访问私有方法。类 Foo 是一个与给定的 Foo 实例不同的对象。
不要将我的答案视为最终答案。我当然不是专家,但我想提供一个代码片段,以便其他尝试回答的人将拥有正确的私有类方法。
其他提示
让我为这个或多或少奇怪的解决方案和非解决方案列表做出贡献:
puts RUBY_VERSION # => 2.1.2
class C
class << self
private def foo
'Je suis foo'
end
end
private define_method :foo, &method(:foo)
def bar
foo
end
end
puts C.new.bar # => Je suis foo
puts C.new.foo # => NoMethodError
如果你的方法只是一个 实用功能 (也就是说,它不依赖于任何实例变量),您可以将该方法放入模块中并 include
和 extend
类,以便它既可用作私有类方法,也可用作私有实例方法。
现在你不再需要辅助方法了。您可以简单地将它们内联到您的方法定义中。对于 Java 人员来说,这应该非常熟悉:
class MyClass
private_class_method def self.my_private_method
puts "private class method"
end
private def my_private_method
puts "private instance method"
end
end
不,您不能从实例方法调用私有类方法。但是,您可以改为实施 私人的 类方法为 民众 中的类方法 私人的 相反,使用嵌套类 private_constant
辅助方法。看 这篇博文 了解更多详情。
这是使用“真正的”私有类方法的方法。
class Foo
def self.private_bar
# Complex logic goes here
puts "hi"
end
private_class_method :private_bar
class <<self
private
def another_private_bar
puts "bar"
end
end
public
def instance_bar
self.class.private_bar
end
def instance_bar2
self.class.another_private_bar
end
def calling_private_method
Foo.send :another_private_bar
self.class.send :private_bar
end
end
f=Foo.new
f.send :calling_private_method
# "bar"
# "hi"
Foo.send :another_private_bar
# "bar"
干杯
这可能是最“原生 Ruby”的方式:
class Foo
module PrivateStatic # like Java
private def foo
'foo'
end
end
extend PrivateStatic
include PrivateStatic
def self.static_public_call
"static public #{foo}"
end
def public_call
"instance public #{foo}"
end
end
Foo.static_public_call # 'static public foo'
Foo.new.public_call # 'instance public foo'
Foo.foo # NoMethodError: private method `foo' called for Foo:Class
Foo.new.foo # NoMethodError: private method `foo' called for #<Foo:0x00007fa154d13f10>
通过一些 Ruby 元编程,您甚至可以使其看起来像:
class Foo
def self.foo
'foo'
end
extend PrivateStatic
private_static :foo
end
Ruby 的元编程非常强大,因此您可以在技术上实现您可能想要的任何范围规则。话虽这么说,我还是更喜欢清晰度和 最小的惊喜 第一个变体。
除非我误会了,否则你不需要这样的东西:
class Foo
private
def Foo.bar
# Complex logic goes here
puts "hi"
end
public
def bar
Foo.bar
end
end
当然,如果您想避免对类名进行硬编码,您可以更改第二个定义以使用 self.class.send 方法...