【问题标题】:Rails - Can't monkey-patch wicked_pdf gemRails - 不能猴子补丁 wicked_pdf gem
【发布时间】:2016-05-03 22:39:49
【问题描述】:

我正在尝试对 wicked_pdf gem 进行猴子补丁,但无法识别我的补丁。

如果我进入 gem 的本地副本中的源代码并修改 WickedPdf 类的 #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

但是,当我尝试实现与猴子补丁相同的想法时,假设在初始化程序中,该修改不会反映。

# 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 类是否存在,并且我已经确认 WickedPdf 类中的其他方法(公共和私有)会发生这种情况。为什么我的猴子补丁无效?

【问题讨论】:

    标签: ruby ruby-on-rails-4 wicked-pdf


    【解决方案1】:

    WickedPdf#print_command 直接在类WickedPdf 中定义(参见the source code),因此它会影响类在模块included 中定义的任何#print_command。要覆盖它的行为,如果您使用的是 Ruby >= 2.0.0,则可以使用 Module#prepend,否则可以使用别名方法链。当然,无论您使用哪个版本的 Ruby,您都可以随时打开类 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)
    

    【讨论】:

      【解决方案2】:

      我认为您需要打开该课程:

      class WickedPdf
        def print_command(cmd)
          puts "\n\nthis is my modification\n\n" 
        end
      end
      

      【讨论】:

        猜你喜欢
        • 2010-09-29
        • 2011-03-26
        • 1970-01-01
        • 2015-08-21
        • 2016-09-01
        • 2012-09-16
        • 2012-12-18
        • 2020-01-09
        • 1970-01-01
        相关资源
        最近更新 更多