有没有一种方法可以从Ruby中的实例调用私有Class方法? [英] Is there a way to call a private Class method from an instance in Ruby?
问题描述
除了 self.class.send之外:方法,参数...
当然。我想在类和实例级别上提供一个相当复杂的方法,而不必复制代码。
Other than self.class.send :method, args...
, of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code.
更新:
@Jonathan Branam:这是我的假设,但我想确保没有其他人找到解决方法。 Ruby中的可见性与Java中的可见性非常不同。您也很正确, private
不适用于类方法,尽管这会声明一个私有类方法:
@Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that private
doesn't work on class methods, though this will declare a private class method:
class Foo
class <<self
private
def bar
puts 'bar'
end
end
end
Foo.bar
# => NoMethodError: private method 'bar' called for Foo:Class
推荐答案
这里是与问题一起出现的代码段。在类定义中使用私有不适用于类方法。您需要使用以下示例中的 private_class_method。
Here is a code snippet to go along with the question. Using "private" in a class definition does not apply to class methods. You need to use "private_class_method" as in the following example.
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实例是一个不同的对象。
I don't see a way to get around this. The documentation says that you cannot specify the receive of a private method. Also you can only access a private method from the same instance. The class Foo is a different object than a given instance of Foo.
别把我的答案当作定论。我当然不是专家,但是我想提供一个代码段,以便其他尝试回答的人将拥有正确的私有类方法。
Don't take my answer as final. I'm certainly not an expert, but I wanted to provide a code snippet so that others who attempt to answer will have properly private class methods.
这篇关于有没有一种方法可以从Ruby中的实例调用私有Class方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!