在 Ruby 中,是否可以在不影响子类代码的情况下从父类(super class)方法中产生子类方法?我试图避免在子类中调用 super
。
class SuperClass
def do_something
puts "getting ready..."
# how to then yield back to the subclass do_something method?
puts "done."
end
end
class SubClass < SuperClass
def do_something
# how to first execute the superclass do_something method?
puts "doing something ..."
end
end
期望的功能是专门调用 SubClass.do_something
并接收以下输出:
“准备……”
“做某事……”
“完成。”
编辑:
也许真正的问题是:如何干燥下面的代码,从所有子类中删除对 self.get_ready
和 self.finish_up
的调用,使用任何 ruby meta - 使这些类保持干燥的编程技术:
class SuperClass
def self.get_ready
puts "getting ready ..."
end
def self.finish_up
puts "done."
end
end
class SubClassA < SuperClass
def self.do_something
self.get_ready
puts "doing something ..."
self.finish_up
end
end
class SubClassB < SuperClass
def self.do_something
self.get_ready
puts "doing something else, a little differently..."
self.finish_up
end
end
class SubClassC < SuperClass
def self.do_something
self.get_ready
puts "doing something crazy..."
self.finish_up
end
end
在Practical Object-Oriented Design in Ruby ,Sandi Metz 建议您克服调用 super 的方法是在父类(super class)中定义一个“ Hook ”方法,唯一的工作就是被子方法覆盖。在你的情况下,你可以这样做:
class SuperClass
def self.do_something
puts "getting ready..."
do_something_child
puts "done."
end
def self.do_something_child; end
end
class SubClass < SuperClass
def self.do_something_child
puts "doing something ..."
end
end
SubClass.do_something
我是一名优秀的程序员,十分优秀!