当rails重新加载类时,初始化程序中的控制器猴子补丁会丢失 [英] Controller monkey patch in initializer gets lost when rails reloads classes

查看:126
本文介绍了当rails重新加载类时,初始化程序中的控制器猴子补丁会丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在第三方宝石猴子补丁控制器类。确切地说,我试图添加参数包装来设计控制器。在 initializers / wrap_parameters.rb 我添加了以下位:

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

当应用程序启动时,它工作得很好,但是当我修改我的一个控制器类时,参数包装将立即停止工作。好像在没有上述补丁的情况下重新加载控制器类。



如何使我的猴子补丁持续?



感谢

解决方案

我以前有一个类似的问题,尝试在rails中加载的monkeypatch代码。我可以通过将我的补丁包装在一个模块中,然后在正在编辑的类中扩展模块来修复它。在配置/初始化器中的新文件中将会是这样的东西:

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

class DeviseController< Devise.parent_controller.constantize
扩展MyDeviseDectorator
end

我可能有一个设计类名错了,它应该匹配任何你想要monkeypatch。我不是100%这个方法会解决你的问题像它固定我的,但试一试;我会留下这个作为评论,但没有最小的代表。


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

解决方案

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.

这篇关于当rails重新加载类时,初始化程序中的控制器猴子补丁会丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆