Sylar Sylar - 4 months ago 22
Ruby Question

Safe and best way to monkey patch a rails gem

I have tried, seriously. Many questions out there but many developers say "It dont work for me"; I'm one of them -- said to say.

I was reading up on the best way to monkey-patch a rails gem. I've found few but decided to use this method.

I want to monkey-patch the xeroizer gem but rather the 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


Going with the "this method" link, I assume this should work, but it dosent.

Controller:

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



undefined method `invoice_url' for Xeroizer::Record::InvoiceModel


How do you add custom methods to a rails gem's class?

Answer

Assuming you are trying to monkey-patch Xeroizer::Record::InvoiceModel with Xeroizer::Invoice::InvoiceUrl, you might just do the following right after the first mention of Xeroizer::Record::InvoiceModel (to make Rails to autoload it):

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

This will override original invoice_url method. The original one still might be called from a prepended using super.

Comments