Reputation: 5329
module B
def stub
extend()
end
def extend
puts "B:extend"
end
end
class A
include B
def extend
puts "A:extend"
end
end
a = A.new
a.stub
# output: A:extend
# would like to have: B:extend
The question is:
How to make a.stub
call extend
method from module B
without modifying B
's code and without renaming A
's method extend
?
Upvotes: 1
Views: 90
Reputation: 9146
My just another try.
A.class_eval do
if self.include? B
def extend
super
end
end
end
A.new.stub
#=> B:extend
Correct me if this is a wrong approach.
Upvotes: 1
Reputation: 21791
def a.extend
self.class.ancestors[1].instance_method(:extend).bind(self).call
end
Upvotes: 1
Reputation: 114218
include B
adds B
's methods to A
so your method definition is overwriting B
's implementation.
You could use the alias
method to save a reference to B
's method and implement your own stub
method in A
:
class A
include B
alias :b_extend :extend
def stub
b_extend
end
def extend
puts "A:extend"
end
end
A.new.stub
# B:extend
Upvotes: 3
Reputation: 10107
Maybe a monkey patch could solve this.
module B
alias original_stub stub
alias b_extend extend
def stub
b_extend
end
end
But if your project does have many calls to original stub... each call should be modified.
Upvotes: 1