为什么extend方法不放置值

问题描述

|
module Lab
  def self.foo
    puts \'foo from lab\'
  end
end

module M
  def foo
    puts \'foo from module\'
    super
  end
end

module Lab
  extend M
end

Lab.foo
我原以为我会看到
foo from module
foo from lab
但是我得到的是
foo from lab
我想做的是从gem截获方法的值并执行某些操作。我可以使用alias_method_chain,但我尝试不使用它。     

解决方法

        如果您期望
foo from module
foo from lab
然后,您需要将super放在Lab#foo中,如下所示:
module Lab
  def self.foo
    super
    puts \'foo from lab\'
  end
end

module M
  def foo
    puts \'foo from module\'
  end
end

module Lab
  extend M
end

Lab.foo
    ,        在?5?上定义的方法直接优先于在?5?扩展的模块(例如?6?)中定义的方法。 因此,直接在
Lab
上定义的
foo
优先于
M#foo
,即使
Lab.extend M
也是如此。 要获得所需的内容,请执行以下操作:
module Lab
  module HasFoo
    # foo isn\'t defined directly on Lab directly anymore;
    # instead,it is defined in a separate module that
    # Lab extends
    def foo
      puts \"foo from lab\"
    end
  end

  extend HasFoo
end

module M
  def foo
    puts \"foo from module\"
    super
  end
end

module Lab
  # when Lab extends another module with foo,that changes
  # which concrete method the name foo gets resolved to
  extend M
end

# now you should see the module foo and then the lab foo
Lab.foo
    ,        当您将模块
M
包含/扩展为类
C
,并调用也为
M
定义的方法
C#method
C.method
时,
C
在方法的搜索路径中将优先于
M
。换句话说,您不能通过包含/扩展来覆盖方法。您只能添加新方法。请参阅此相关问题。 在您的情况下,简单地称为
Lab.foo
。以下内容(无
Lab.foo
)将为您提供所需的结果。
module M
  def foo
    puts \'foo from module\'
  end
end

module Lab
  extend M
end

Lab.foo

# => foo from module
请注意,您的
M
的超类是
Module
,并且由于未定义
Module#foo
,因此以下内容将导致错误。
module M
  def foo
    puts \'foo from module\'
    super
  end
end

module Lab
  extend M
end

Lab.foo

# => method undefined error
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...