如何在使用异常通知gem初始化后访问异常收件人?

时间:2013-10-11 23:26:00

标签: ruby-on-rails-3 activerecord exception-notification

我希望能够基于Rails环境动态定义exception_recipients。例如:

recipients = Rails.env == 'production'
   exceptions@myapp.com
else
   User.current.email
end

然而,来自文档:

Whatever::Application.config.middleware.use ExceptionNotification::Rack,
  :email => {
    :email_prefix => "[Whatever] ",
    :sender_address => %{"notifier" <notifier@example.com>},
    :exception_recipients => %w{exceptions@example.com}
  }

config/environments/production.rb我还没有ActiveRecord::Base连接。

如何在加载Rails后设置例外收件人?

由于

2 个答案:

答案 0 :(得分:1)

自定义通知程序

您可以创建一个自定义通知程序,该通知程序继承自EmailNotifier,它将在非生产环境中使用User.current.email

# app/models/exception_notifier/custom_notifier.rb
#
module ExceptionNotifier
  class CustomNotifier < EmailNotifier

    def initialize(options)
      @fallback_exception_recipients = options[:fallback_exception_recipients]
      options[:exception_recipients] ||= options[:fallback_exception_recipients]
      super(options)
    end

    def call(exception, options = {})
      options[:exception_recipients] = [User.current.email] unless Rails.env.production?
      super(exception, options)
    end

  end
end

初始化程序

例如,可以从初始化程序传递回退地址。

# config/initializers/exception_notification.rb
#
Rails.application.config.middleware.use ExceptionNotification::Rack, {
  :custom => {
    :fallback_exception_recipients => %w{exceptions@myapp.com},
    # ...
  }
}

current_user代替User.current

我不确定您的User.current来电是否有效。但是,您将current_user传递给异常数据,如README

所示
# app/controllers/application_controller.rb
#
class ApplicationController < ActionController::Base
  before_filter :prepare_exception_notifier
  private
  def prepare_exception_notifier
    request.env["exception_notifier.exception_data"] = {
      :current_user => current_user
    }
  end
end

然后,用以下方法替换上面的ExceptionNotifier::CustomNotifier#call方法:

# app/models/exception_notifier/custom_notifier.rb
#
module ExceptionNotifier
  class CustomNotifier < EmailNotifier

    # ...

    def call(exception, options = {})
      unless Rails.env.production?
        if current_user = options[:env]['exception_notifier.exception_data'][:current_user]
          options[:exception_recipients] = [current_user.email]
        end
      end
      super(exception, options)
    end

  end
end

答案 1 :(得分:0)

不支持开箱即用。您可以按照文档https://github.com/smartinez87/exception_notification#custom-notifier

中的说明创建自己的自定义通知程序

您可以查看内置的EmailNotifier并可能对其进行扩展,并覆盖initializecompose_email方法,以使其满足您的需求。

https://github.com/smartinez87/exception_notification/blob/master/lib/exception_notifier/email_notifier.rb#L120

https://github.com/smartinez87/exception_notification/blob/master/lib/exception_notifier/email_notifier.rb#L90