我在我想隐藏的第三方gem的超类中有一个方法。我宁愿如果根本不可能调用这个方法,那么不仅仅是覆盖它并且让它空着。如何隐藏超类的方法?
3
A
回答
3
我认为这可能是你在找什么:
undef_method :foo
这将防止方法foo
任何来电。
相反,这不会达到同样的效果:
remove_method :foo
将从孩子的方法去掉,但仍然会通过了继承链。
2
这是错误的OOP,你要在那里做。我建议你使用组合而不是继承。
require 'forwardable'
class SomeBaseClass
def foo
puts 'foo'
end
def bar
puts 'bar'
end
def quux
puts 'quux'
end
end
class MyClass
def initialize
@base = SomeBaseClass.new
end
extend Forwardable
def_delegators :@base, :foo, :bar # but not quux
end
mc = MyClass.new
mc.foo
mc.bar
mc.quux
# >> foo
# >> bar
# ~> -:32:in `<main>': undefined method `quux' for #<MyClass:0x007febcc155210> (NoMethodError)
+0
这是一个非常有趣的设计模式。以前没见过。你碰巧知道为什么存在一个'undef'关键字,当这是这样做的更好的方法吗? – Nessuno
+1
@Nessuno:因为Ruby非常灵活。而“更好”是主观的。 :) –
3
使用undef
关键字。
class A
def foo
5
end
end
class B < A
undef foo
end
A.new.foo #=> 5
B.new.foo #=> NameError: undefined local variable or method `foo'
相关问题
- 1. 超类的隐藏方法
- 2. 如何在eclipse中隐藏Content Assist中的超类方法?
- 3. 如何在Java中完全隐藏超类的方法
- 4. 如何从基类中隐藏方法?
- 5. 从子类的用户隐藏超类方法
- 6. 在ObjC中,我如何隐藏一个子类中超类方法的实现?
- 7. getDeclaredMethods()和隐藏的超类静态方法
- 8. 方法隐藏
- 9. Java中,隐藏超级超级类
- 10. java中的隐藏方法和类(Robotium)
- 11. 带有“隐藏”方法的C#类
- 12. 隐藏基类中的方法
- 13. 子类中的隐藏方法
- 14. 如何隐藏F#中的方法?
- 15. Objective-C - 如何隐藏实现协议的类的方法
- 16. 如何隐藏我的子类中的方法?
- 17. C# - 如何隐藏派生类的Web方法
- 18. 如何隐藏可继承类中的公共方法
- 19. 如何隐藏派生类中的公共方法?
- 20. 如何隐藏自定义类中的某些方法?
- 21. Python'隐藏'方法__
- 22. C#方法隐藏
- 23. 使用.call/.apply隐藏类方法
- 24. 路线在笨隐藏类方法
- 25. 从XML文档隐藏类/方法
- 26. 在类中隐藏了一些方法
- 27. 如何从COM中隐藏GetType()方法?
- 28. 如何从Spring bean中隐藏方法?
- 29. 如何隐藏配置方法?
- 30. 如何正确隐藏基方法
其实在这种情况下很难选择“正确答案”。我喜欢这种方式,因为它更简洁,我不必为所有我想使用的功能编写一个委托(这是很多),但我认为在某些情况下最好使用Sergio Tulentsev的答案 – Nessuno