ruby-on-rails - Rails 4 ActionMailer around_action |访问操作信息(操作名称和参数)

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

我正在为我的 customer_mailer 类构建一个 around_action,这样我就不必每次都在 begin and rescue 周围包装调用deliver_now

class CustomerMailer < ApplicationMailer
  around_action :rescue_error

  def send_email(customer)
    ...
  end

  def invite_friend(customer, invitee_email)
    ...
  end

  private
    def rescue_error
      yield
    rescue => e
      msg = "Caught exception! #{e} | #{action_name}"
      puts msg
      raise
     end
end

所以在救援中,我想记录消息,其中包含调用了哪个操作等信息,我设法找到方法 action_name 来显示调用了哪个操作,但我找不到检索传递给操作的参数的方法,有什么想法吗?

谢谢!

最佳答案

在我回答你的问题之前:使用 Bugsnag 或类似的东西对你的情况有用吗?或者 rescue_from Exception, with: :exception_handler 对你有用吗? (虽然它不允许您重新引发异常)


我深入研究了 Rails 源代码,似乎参数没有存储在任何地方。它们只是作为 splat 传递给邮件程序类中定义的实例方法。但是, 有一种存储它们的方法(无需猴子修补)。

邮件程序继承自 AbstractController::Base。查看下面的代码片段:

  # Call the action. Override this in a subclass to modify the
  # behavior around processing an action. This, and not #process,
  # is the intended way to override action dispatching.
  #
  # Notice that the first argument is the method to be dispatched
  # which is *not* necessarily the same as the action name.
  def process_action(method_name, *args)
    send_action(method_name, *args)
  end

  # Actually call the method associated with the action. Override
  # this method if you wish to change how action methods are called,
  # not to add additional behavior around it. For example, you would
  # override #send_action if you want to inject arguments into the
  # method.
  alias send_action send

我们可以看到我们可以覆盖 #send_action 并让它存储参数。将以下内容添加到您的 ApplicationMailer:

class ApplicationMailer < ActionMailer::Base
  def send_action(method_name, *args)
    @action_args = args
    super
  end
end

参数将作为 @action_args 在您的所有邮件程序中可用。

关于ruby-on-rails - Rails 4 ActionMailer around_action |访问操作信息(操作名称和参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37661969/

相关文章:

ruby-on-rails - 需要 Rails bundle 安装密码

ruby-on-rails - Ruby-on-Rails 的文本编辑器

ruby-on-rails - 链接以在 Ruby On Rails 中显示

ruby - 如何验证嵌入字段是否在 before_save 上发生了变化?

ruby-on-rails - 我不明白这个? (Rails 上的 ruby )

ruby-on-rails - rails 4 before_validation on : :create or on: :save

javascript - 将 onChange 事件放在选择框中

ruby-on-rails - 使用 Ajax 的 RoR 主从细节

ruby-on-rails - rails : control file store cache size

ruby - 使用redis和ruby实现一个小型短网址应用程序