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

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

问题描述

我正在尝试在第三方 gem 中修改控制器类.准确地说,我正在尝试添加参数包装来设计控制器.在 initializers/wrap_parameters.rb 中,我添加了以下内容:

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?

谢谢

推荐答案

我之前在尝试对在 Rails 中延迟加载的猴子补丁代码时遇到过类似的问题.我能够通过将我的补丁包装在一个模块中然后在您正在编辑的类中扩展该模块来修复它.在 config/initializers 中的新文件中将是这样的:

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

我的设计类名称可能有误,它应该与您尝试使用的monkeypatch 匹配.我不是 100% 这个方法会解决你的问题,就像它解决我的问题一样,但试试看;我会留下这个作为评论,但没有最低代表.

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天全站免登陆