Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller monkey patch in initializer gets lost when rails reloads classes

I am trying to monkey patch controller classes in a third party gem. To be precise, I am trying to add parameter wrapping to devise controllers. In initializers/wrap_parameters.rb I added the following bit:

Rails.application.config.after_initialize do
  DeviseController.class_eval do
    wrap_parameters :user, format: [:json]
  end
end

It works great when the application starts, but when I modify one of my controller classes, the parameter wrapping stops working immediately. As if the controller class was reloaded without the above patch.

How to make my monkey patch persistent?

Thanks

like image 203
nakhli Avatar asked Nov 10 '22 00:11

nakhli


1 Answers

I had a similar issue before with trying to monkeypatch code that is lazy loaded in rails. I was able to fix it by wrapping my patch in a module then extending the module in the class you are editing. It would be something like this inside a new file in config/initializers:

module MyDeviseDecorator
  wrap_parameters :user, format: [:json]
end

class DeviseController < Devise.parent_controller.constantize
    extend MyDeviseDectorator
end

I may have a devise class name wrong, it should match whatever you are trying to monkeypatch. Im not 100% this method will fix your problem like it fixed mine but give it a try; I would have left this as a comment but didnt have the minimum rep.

like image 199
MattHamada Avatar answered Nov 14 '22 23:11

MattHamada