【问题标题】:Safe and best way to monkey patch a rails gem猴子修补rails gem的安全和最佳方法
【发布时间】:2016-08-02 06:44:19
【问题描述】:

我试过了,认真的。那里有很多问题,但许多开发人员说“它不适合我”;我就是其中之一——据说。

我正在阅读猴子修补 rails gem 的最佳方法。我找到了few,但决定使用this method

我想对xeroizer gem 进行猴子补丁,而不是invoice.rb model

# lib/xeroizer/invoice/invoice_url.rb

module Xeroizer
  module Invoice
    module InvoiceUrl
      def invoice_url(id)
        @application.http_get(@application.client, "#{url}/#{CGI.escape(id)}/OnlineInvoice")
      end
    end
  end
end

使用“此方法”链接,我认为这应该可以工作,但它并不重要。

控制器:

include Xeroizer::Invoice::InvoiceUrl
# Invoice.include Xeroizer::Invoice::InvoiceUrl

def some_method
  # @xero is in a private method. It's here for short demonstration
  @xero = Xeroizer::PrivateApplication.new("MY_CONSUMER_KEY", "MY_SECRET_KEY", "#{Rails.root}/privatekey.pem")
  Rails.logger = @xero.Invoice.invoice_url("ad61ea97-b9e9-4a1e-b754-7c19e62f8cd7")
end

Xeroizer::Record::InvoiceModel 的未定义方法 `invoice_url'

如何将自定义方法添加到 rails gem 的类?

【问题讨论】:

  • 您可以尝试将您的代码作为初始化程序
  • @Alfie 我想我已经尝试过使用Xeroizer::PrivateApplication.class_eval ...,但从未奏效。可能我没做对。
  • 我没有看到任何猴子修补任何东西的尝试。请您详细说明您要达到的目标吗?
  • @mudasobwa 这是我第一次尝试“猴子补丁”,我认为这意味着向 gem 添加自定义方法?没有?

标签: ruby-on-rails ruby ruby-on-rails-4 rubygems


【解决方案1】:

假设您尝试使用 Xeroizer::Invoice::InvoiceUrlXeroizer::Record::InvoiceModel 进行猴子补丁,您可能只需在第一次提到 Xeroizer::Record::InvoiceModel 之后执行以下操作(让 Rails 自动加载它):

Xeroizer::Record::InvoiceModel.prepend Xeroizer::Invoice::InvoiceUrl

这将覆盖原来的invoice_url 方法。原始的仍然可以从使用 super 的前缀中调用。

【讨论】:

  • invoice_url 是一种自定义方法,它不在 gem 中。我想在InvoiceModel 中添加一个自定义方法(invoice_url)。
  • 好的。我现在得到了wrong number of arguments (given 1, expected 0)。我的模块正确吗?我有invoice_url(id),当它说预期为 0 时,它需要一个参数。为什么?
  • “我现在的参数数量错误(给定 1,预期为 0)”——我不是算命先生。请分享堆栈跟踪。另外,请确保原始Xeroizer::Record::InvoiceModel 没有名为invoice_url 的方法。如果是这样,您可以通过将默认值添加到参数来解决问题:def invoice_url(id = nil)
  • 哦!!!!!!我应该使用 puts 而不是 Rails.logger 它工作 OMG!有用!!!谢谢!!!!!!
猜你喜欢
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 2017-02-12
  • 1970-01-01
  • 2015-03-23
相关资源
最近更新 更多