猴子补丁魔法(或任何Rails宝石) [英] Monkey patching Devise (or any Rails gem)
问题描述
所以我想以某种方式覆盖 set_flash_message
方法在 DeviseController 。
这是新的方法:
def set_flash_message(key ,kind,options = {})
如果key =='alert'
key ='error'
elsif key =='notice'
key ='成功'
end
message = find_message(kind,options)
flash [key] = message if message.present?
end
但我只是不知道在哪里放。
更新:
根据答案,我创建了一个配置/ initializers / overrides.rb文件,其代码如下:
class DeviseController
def set_flash_message(key,kind,options = {})
如果key =='alert'
key ='error'
elsif key =='notice'
key ='成功'
end
message = find_message(kind,options)
flash [key] = message if message.present?
end
end
但是这会导致每个Devise操作发生错误: / p>
路由错误:未定义的方法'prepend_before_filter'为
Devise :: SessionsController:Class
< blockquote>
解决方案如果您尝试重新打开一个类,它与声明新类的语法相同:
class DeviseController
end
如果这个代码在真正的类声明之前执行,它将继承自Object而不是扩展Devise声明的类。相反,我尝试使用以下
DeviseController.class_eval do
#您的新方法
end
这样一来,如果
DeviseController
尚未声明。因此,您最终可能会遇到require'devise / app / controllers / devise_controller'
DeviseController.class_eval do
#您的新方法
end
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.Here's the new method:
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.
UPDATE:
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:
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
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
This way, you'll get an error if
DeviseController
has not been declared. As a result, you'll probably end up withrequire 'devise/app/controllers/devise_controller' DeviseController.class_eval do # Your new methods here end
这篇关于猴子补丁魔法(或任何Rails宝石)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!