Rails - 不能猴子补丁 wicked_pdf gem
Rails - Can't monkey-patch wicked_pdf gem
我正在尝试对 wicked_pdf gem 进行猴子补丁,但我的补丁未被识别。
如果我在 gem 的本地副本中进入源代码并修改 WickedPdf class 的 #print_command method,我的修改会在我查看时反映在日志中pdf.
# local/gem/path/lib/wicked_pdf.rb
def print_command(cmd)
puts "\n\nthis is my modification\n\n" # appears in logs
end
然而,当我尝试实现与 monkey-patch 相同的想法时,假设在初始化程序中,修改没有反映出来。
# config/initializers/wicked_pdf.rb
module WickedPdfExtension
def print_command(cmd)
puts "\n\nthis is my modification\n\n" # does not appear in logs
end
end
WickedPdf.include(WickedPdfExtension)
我已经检查过 WickedPdf
class 在我扩展它时是否存在,并且我已经确认其他方法也会发生这种情况,public 和 private , 在 WickedPdf
class 中。为什么我的猴子补丁无效?
WickedPdf#print_command
直接在 class WickedPdf
中定义(参见 the source code),因此它隐藏了模块 [=15] 中定义的任何 #print_command
=]d 由 class。要覆盖它的行为,如果您使用 Ruby >= 2.0.0,则可以使用 Module#prepend
,否则使用别名方法链。当然,无论您使用的 Ruby 是哪个版本,您都可以随时打开 class WickedPdf
并重新定义方法。
使用Module#prepend
module WickedPdfExtension
def print_command(cmd)
puts "\n\nthis is my modification\n\n"
end
end
WickedPdf.prepend(WickedPdfExtension)
使用别名方法链
module WickedPdfExtension
extends ActiveSupport::Concern
included do
def print_command_with_modification(cmd)
puts "\n\nthis is my modification\n\n"
end
alias_method_chain :print_command, :modification
end
end
WickedPdf.include(WickedPdfExtension)
我想你需要打开 class:
class WickedPdf
def print_command(cmd)
puts "\n\nthis is my modification\n\n"
end
end
我正在尝试对 wicked_pdf gem 进行猴子补丁,但我的补丁未被识别。
如果我在 gem 的本地副本中进入源代码并修改 WickedPdf class 的 #print_command method,我的修改会在我查看时反映在日志中pdf.
# local/gem/path/lib/wicked_pdf.rb
def print_command(cmd)
puts "\n\nthis is my modification\n\n" # appears in logs
end
然而,当我尝试实现与 monkey-patch 相同的想法时,假设在初始化程序中,修改没有反映出来。
# config/initializers/wicked_pdf.rb
module WickedPdfExtension
def print_command(cmd)
puts "\n\nthis is my modification\n\n" # does not appear in logs
end
end
WickedPdf.include(WickedPdfExtension)
我已经检查过 WickedPdf
class 在我扩展它时是否存在,并且我已经确认其他方法也会发生这种情况,public 和 private , 在 WickedPdf
class 中。为什么我的猴子补丁无效?
WickedPdf#print_command
直接在 class WickedPdf
中定义(参见 the source code),因此它隐藏了模块 [=15] 中定义的任何 #print_command
=]d 由 class。要覆盖它的行为,如果您使用 Ruby >= 2.0.0,则可以使用 Module#prepend
,否则使用别名方法链。当然,无论您使用的 Ruby 是哪个版本,您都可以随时打开 class WickedPdf
并重新定义方法。
使用Module#prepend
module WickedPdfExtension
def print_command(cmd)
puts "\n\nthis is my modification\n\n"
end
end
WickedPdf.prepend(WickedPdfExtension)
使用别名方法链
module WickedPdfExtension
extends ActiveSupport::Concern
included do
def print_command_with_modification(cmd)
puts "\n\nthis is my modification\n\n"
end
alias_method_chain :print_command, :modification
end
end
WickedPdf.include(WickedPdfExtension)
我想你需要打开 class:
class WickedPdf
def print_command(cmd)
puts "\n\nthis is my modification\n\n"
end
end