在 Ruby 中调用超级模块中的重写方法
Calling overridden method in super module in Ruby
在下面的代码中,Parent#just_do
覆盖了 GrandParent#just_do
。在Me
class中,如何调用GrandParent#just_do
?
module GrandParent
def just_do
puts "GrandParent"
end
end
module Parent
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
include GrandParent
def just_do
puts "Parent"
end
end
end
class Me
include Parent
def self.just_do
super # this calls Parent#just_do
end
end
您无法真正取消覆盖某些内容。在这种特殊情况下,您可以重新导入它,但这可能会产生其他副作用。
"Parent" 最好保留原件,因为可能需要调用它:
module GrandParent
def just_do
puts "GrandParent"
end
end
module Parent
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
include GrandParent
# Creates an alias to the original method
alias_method :grandpa_just_do, :just_do
def just_do
puts "Parent"
end
end
end
class Me
include Parent
def self.just_do
# Call using the alias created previously
grandpa_just_do
end
end
Me.just_do
您可以直接使用 method object。
class Me
include Parent
def self.just_do
method(:just_do).super_method.super_method.call
end
end
在下面的代码中,Parent#just_do
覆盖了 GrandParent#just_do
。在Me
class中,如何调用GrandParent#just_do
?
module GrandParent
def just_do
puts "GrandParent"
end
end
module Parent
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
include GrandParent
def just_do
puts "Parent"
end
end
end
class Me
include Parent
def self.just_do
super # this calls Parent#just_do
end
end
您无法真正取消覆盖某些内容。在这种特殊情况下,您可以重新导入它,但这可能会产生其他副作用。
"Parent" 最好保留原件,因为可能需要调用它:
module GrandParent
def just_do
puts "GrandParent"
end
end
module Parent
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
include GrandParent
# Creates an alias to the original method
alias_method :grandpa_just_do, :just_do
def just_do
puts "Parent"
end
end
end
class Me
include Parent
def self.just_do
# Call using the alias created previously
grandpa_just_do
end
end
Me.just_do
您可以直接使用 method object。
class Me
include Parent
def self.just_do
method(:just_do).super_method.super_method.call
end
end