【问题标题】:Rails add 'rescue_from' method to application controller from patch//pluginRails 从补丁//插件向应用程序控制器添加“rescue_from”方法
【发布时间】: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)
  1. 此堆栈溢出链接中的解决方案: How do I require ActiveSupport's rescue_from method?

到目前为止,似乎没有一种方法有效。 如果上述代码有错误,请提供任何解决方案或帮助更正。

【问题讨论】:

  • 只需在 ApplicationController 中包含一个模块,而不是尝试从外部对其进行修补。否则你必须担心monkeypatch何时执行。
  • 我无法更改核心 Rails 应用程序中的代码,因此需要猴子补丁。

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

在这里我做了同样的事情并测试它对我来说效果很好。下面是我的模块。我已添加到 Applicationlib/exception_data_redirection

module ExceptionDataRedirection
  extend ActiveSupport::Concern
  included do
    rescue_from ActiveRecord::RecordNotFound do |exception|
      redirect_to items_path
    end
  end
 end

items_path 将是重定向网址

在 application.rb 中——添加以下行

 config.autoload_paths += %W(#{config.root}/lib)

重启服务器....

然后是 ApplicationController -- 包含模块

  include ExceptionDataRedirection

这就像一个魅力,你也可以这样做

module ExceptionDataRedirection

  def self.included(base)
    base.class_eval do
      rescue_from ActiveRecord::RecordNotFound do |exception|
        redirect_to items_path
      end
    end
  end
end

如果有任何问题请告诉我

【讨论】:

    猜你喜欢
    • 2011-07-26
    • 2016-11-25
    • 1970-01-01
    • 2010-11-06
    • 2017-01-31
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多