【发布时间】:2018-03-24 09:59:21
【问题描述】:
我正在尝试通过插件修补我的 Rails(4.2.5) 应用程序的 ApplicationController。 我想将 'rescue_from ActiveRecord::RecordNotFound' 添加到我的 ApplicationController。到目前为止我尝试过的方式:
1.
module ApplicationControllerPatch
def self.included(base)
base.class_eval do
rescue_from ActiveRecord::RecordNotFound do |e|
redirect_to root_path
end
end
end
end
ApplicationController.send(:include, ApplicationControllerPatch)
2.
module ApplicationControllerPatch
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
rescue_from ActiveRecord::RecordNotFound, with: :not_found
end
end
module InstanceMethods
def not_found
redirect_to root_path
end
end
end
ApplicationController.send(:include, ApplicationControllerPatch)
此堆栈溢出链接中的解决方案: How do I require ActiveSupport's rescue_from method?
到目前为止,似乎没有一种方法有效。 如果上述代码有错误,请提供任何解决方案或帮助更正。
【问题讨论】:
-
只需在 ApplicationController 中包含一个模块,而不是尝试从外部对其进行修补。否则你必须担心monkeypatch何时执行。
-
我无法更改核心 Rails 应用程序中的代码,因此需要猴子补丁。
标签: ruby-on-rails ruby ruby-on-rails-4