为什么"include"没有对我的模块使用我的猴子路径方法?



我使用的是RubyonRails 6.1.4.4。我想覆盖gem中的一个方法,它的签名是这个

module Juixe
module Acts
module Commentable
module ClassMethods
def acts_as_commentable(*args)
…
end
end
end
end
end

因此,我尝试创建一个文件lib/ext/acts_as_commentable_extensions.rb,并包含以下代码

require 'acts_as_commentable'
module GemExtensions
module Commentable
def hello
print "hellon"
end
def acts_as_commentable(*args)
abcdef
end
end
end
module Juixe
module Acts
module Commentable
module ClassMethods
include GemExtensions::Commentable
end
end
end
end
Juixe::Acts::Commentable::ClassMethods.instance_method(:hello).source.display
Juixe::Acts::Commentable::ClassMethods.instance_method(:acts_as_commentable).source.display

虽然第一条语句从我的新方法"hello"中打印出正确的源代码,但第二条语句从原始gem中打印出旧的源代码(而不是我的新代码(。如何用自己的代码覆盖此方法?

尝试prepend GemExtensions::Commentable而不是include,这将使Ruby首先在前置模块中搜索方法。此处提供更多解释https://medium.com/@leo_setsch/ruby-modules-include-vs-repend-vs-extend-f09837a5b073

最新更新