Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ruby192:特定方法调用_Ruby - Fatal编程技术网

ruby192:特定方法调用

ruby192:特定方法调用,ruby,Ruby,问题是: 如何从模块B中调用extend方法而不修改B的代码,也不重命名a的方法extend?也许猴子补丁可以解决这个问题 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 #

问题是:

如何从模块
B
中调用
extend
方法而不修改
B
的代码,也不重命名
a
的方法
extend

也许猴子补丁可以解决这个问题

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

但是如果您的项目确实有许多对原始存根的调用。。。每个调用都应该修改。

也许猴子补丁可以解决这个问题

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

但是如果您的项目确实有许多对原始存根的调用。。。应修改每个调用。

包含B
B
的方法添加到
A
,因此您的方法定义将覆盖
B
的实现

您可以使用
alias
方法保存对
B
方法的引用,并在
a
中实现自己的
stub
方法:

module B
  alias original_stub stub
  alias b_extend extend
  def stub
    b_extend
  end
end

include B
B
的方法添加到
A
中,因此您的方法定义将覆盖
B
的实现

您可以使用
alias
方法保存对
B
方法的引用,并在
a
中实现自己的
stub
方法:

module B
  alias original_stub stub
  alias b_extend extend
  def stub
    b_extend
  end
end
我的朋友只是再试一次

def a.extend
  self.class.ancestors[1].instance_method(:extend).bind(self).call
end
如果这是一个错误的方法,请纠正我。

我的建议只是再试一次

def a.extend
  self.class.ancestors[1].instance_method(:extend).bind(self).call
end

如果这是一种错误的方法,请纠正我。

只是为了澄清,
stub
来自RSpec gem,因此我询问了
B
代码未被修改的解决方案。只是为了澄清,
stub
来自RSpec gem,所以我询问了
B
代码未被修改的解决方案。