Ruby - How to mimic super for class method?
For (auto-)educational purposes, I'm trying to mimic the super
behavior to learn how it works.
I could mimic super
for instance methods, but I couldn't do it for class methods.
Here is my code:
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)
Any ideas?
Well, the problem is probably the version of Ruby that you are using. I'm running 1.9.2, and the program runs as expected. I think (from the comment in your code) that the problem is that you are running Ruby v1.8.7. It also wouldn't hurt to try running your code again.
精彩评论