Controller monkey patch in initializer gets lost when rails reloads classes

拥有回忆 提交于 2019-12-01 05:23:51

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/26585129/controller-monkey-patch-in-initializer-gets-lost-when-rails-reloads-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!