对于(自动)教育目的,我试图模仿super
行为来了解它的工作原理。Ruby - 如何模仿超类方法?
我可以模仿super
作为实例方法,但我无法为类方法做到这一点。
这里是我的代码:
class A
def aa
@msg ||= 'Original...: '
puts "#{@msg}#{self}.aa: #{self.class} < #{self.class.superclass}"
end
def self.ab
@msg ||= 'Original...: '
puts "#{@msg}#{self}.ab: #{self} < #{self.superclass}"
end
end
class B < A
def aa
@msg = "Real super.: "
super
end
def self.ab
@msg = "Real super.: "
super
end
def mimic_aa
@msg = "Mimic super: "
self.class.superclass.instance_method(:aa).bind(self).call
end
def self.mimic_ab
@msg = "Mimic super: "
#superclass.method(:ab).unbind.bind(self).call
#=> Error: singleton method only works in original object
#superclass.ab
#=> self is A; I want self to be B
proc = superclass.method(:ab).to_proc
#self.instance_eval(&proc)
#=> ArgumentError: instance_eval seems to call aa(some_unwanted_param)
# Note: Ruby 1.8.7
#eval('proc.call', binding)
#=> self is A; I want self to be B
end
end
a = A.new
b = B.new
a.aa #=> Original...: #<A:0xb77c66ec>.aa: A < Object
b.aa #=> Real super.: #<B:0xb77c6624>.aa: B < A
b.mimic_aa #=> Mimic super: #<B:0xb77c6624>.aa: B < A
puts ''
A.ab #=> Original...: A.ab: A < Object
B.ab #=> Real super.: B.ab: B < A
B.mimic_ab #=> (expected the same as above)
任何想法?
你的问题太复杂了,不清楚。我想这就是为什么你的问题到目前为止还没有得到解答。你想用'B#mimic_aa'和'B.mimic_ab'做什么?为什么'B#aa'和'B.ab'不够?另外,方法名称很混乱。你可能想改善这个问题。 – sawa 2011-04-25 01:36:13
@sawa,我想了解如何在B作为'self'的上下文中执行A中的类方法。当A和B中的方法名称不同时,它会很有用,所以我不能使用'super'。无论如何,谢谢你,我会考虑改进这个问题。 :) – 2011-04-25 01:59:26