在运行时将实例方法设为私有 [英] Make instance methods private in runtime
本文介绍了在运行时将实例方法设为私有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在另一个对象中注册该对象后,我需要将一些实例方法设为私有。
I need to make some instance methods private after registering that object in another object.
我不想冻结该对象,因为该对象必须保持可编辑状态,并且功能较少。而且我不想取消定义方法,因为它们在内部使用。
I don't want to freeze the object because it must remain editable, only with less functionality. And I don't want to undef the methods since they are used internally.
我需要的是这样的东西:
What I need is something like:
class MyClass
def my_method
puts "Hello"
end
end
a = MyClass.new
b = MyClass.new
a.my_method #=> "Hello"
a.private_instance_method(:my_method)
a.my_method #=> NoMethodError
b.my_method #=> "Hello"
有什么想法吗?
推荐答案
每个类 是什么是公开的,什么是私有的。但是每个对象都可以有自己的类:
What's public and what's private is per class. But each object can have its own class:
class Foo
private
def private_except_to_bar
puts "foo"
end
end
class Bar
def initialize(foo)
@foo = foo.dup
class << @foo
public :private_except_to_bar
end
@foo.private_except_to_bar
end
end
foo = Foo.new
Bar.new(foo) # => "foo"
foo.private_except_to_bar
# => private method `private_except_to_bar' called for #<Foo:0xb7b7e550> (NoMethodError)
但是。考虑以下替代方案:
But yuck. Consider these alternatives:
- 只需公开该方法即可。
- 探索替代设计。
这篇关于在运行时将实例方法设为私有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文