Monkey 修补设计(或任何 Rails gem) [英] Monkey patching Devise (or any Rails gem)

查看:13
本文介绍了Monkey 修补设计(或任何 Rails gem)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 项目中使用了 Devise 身份验证 gem,我想更改密钥它用于闪光警报.(设计使用 :notice 和 :alert flash 键,但我想将它们更改为 :success 和 :error 以便我可以使用 引导程序.)

I'm using the Devise authentication gem in my Rails project, and I want to change the keys it's using in flash alerts. (Devise uses :notice and :alert flash keys, but I want to change them to :success and :error so that I can display nice green/red boxes with Bootstrap.)

所以我希望能够以某种方式覆盖 设计控制器.

So I want to be able to somehow override the set_flash_message method in DeviseController.

这是新方法:

def set_flash_message(key, kind, options = {})

  if key == 'alert'
    key = 'error'
  elsif key == 'notice'
    key = 'success'
  end

  message = find_message(kind, options)
  flash[key] = message if message.present?

end

但我就是不知道把它放在哪里.

But I just don't know where to put it.

更新:

根据答案,我使用以下代码创建了一个 config/initializers/overrides.rb 文件:

Based on an answer I created a config/initializers/overrides.rb file with the following code:

class DeviseController
    def set_flash_message(key, kind, options = {})
       if key == 'alert'
          key = 'error'
       elsif key == 'notice'
          key = 'success'
       end
       message = find_message(kind, options)
       flash[key] = message if message.present?
    end
end

但这会导致每个设计操作出错:

But this causes an error on every Devise action:

路由错误:未定义方法 'prepend_before_filter' for设计::SessionsController:Class

Routing Error: undefined method 'prepend_before_filter' for Devise::SessionsController:Class

推荐答案

如果您尝试重新打开一个类,其语法与声明一个新类的语法相同:

If you try to reopen a class, it's the same syntax as declaring a new class:

class DeviseController
end

如果这段代码在真正的类声明之前执行,它继承自Object而不是扩展Devise声明的类.相反,我尝试使用以下内容

If this code is executed before the real class declaration, it inherits from Object instead of extending the class declared by Devise. Instead I try to use the following

DeviseController.class_eval do
  # Your new methods here
end

这样,如果 DeviseController 没有被声明,你会得到一个错误.结果,你可能会得到

This way, you'll get an error if DeviseController has not been declared. As a result, you'll probably end up with

require 'devise/app/controllers/devise_controller'

DeviseController.class_eval do
  # Your new methods here
end

这篇关于Monkey 修补设计(或任何 Rails gem)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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