我想将特定消息发送给超类(参见示例)。基于原型的继承非常简单(因为我可以将消息发送到我的原型),但我很难在Ruby中做到这一点。
以下是我想做的简化示例
class BaseService
def say_hello
puts "hello"
end
end
class SpecificService < BaseService
def say_hello
puts "hey you!"
super
end
def say_hello_and_goodbye
# send superclass the :say_hello message
#
# Couldn't find any references to superclass in docs,
# so I make one up to show what I'd like to do.
#
# super.say_hello doesn't work either because super
# looks up the superclass method :say_hello_and_goodbye
superclass.say_hello
puts "goodbye"
end
end
SpecificService.new.say_hello
=> "hey you!"
=> "hello"
SpecificService.new.say_hello_and_goodbye
=> undefined local variable or method `superclass'
# desired
=> "hello"
=> "goodbye"
这个例子是人为的,但它证明了我的问题。反正我是否可以直接将消息传递给基类ala原型继承?
答案 0 :(得分:4)
如果SpecificService
覆盖了要在父级上调用的方法,则需要保存原始(父级)方法的句柄。查看alias_method。
class SpecificService < BaseService
alias_method :original_say_hello, :say_hello
def say_hello
puts "hey you!"
super
end
def say_hello_and_goodbye
original_say_hello
puts "goodbye"
end
end