在Action Mailer中设置实例变量? [英] Setting instance variables in Action Mailer?

查看:65
本文介绍了在Action Mailer中设置实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Mailers中设置实例变量的一种干净的常规方法是什么?当前,我已经在 Mailer 中重新定义了 initialize 方法,并随后在需要的任何邮件程序中覆盖了某些实例变量。

I am wondering what is a clean and conventional way for setting instance variables in Mailers? Currently, I have re-defined the initialize method in Mailer and subsequently overwrite certain instance variables when needed in any mailers that inherit from Mailer.

class Mailer < ActionMailer::Base
  attr_reader :ivar

  def initialize
    super
    @ivar = :blah
    ...
  end
end

这对我来说似乎很奇怪,因为 new 是邮件程序的专用方法。例如,如果要尝试在Rails控制台中检索这些内容,则需要执行以下操作:

This only seems weird to me because new is a private method for mailers. For example, if I were to try to retrieve these in the rails console, I need to do the following:

mailer = Mailer.send(:new)
mailer.ivar

我也考虑过将它们添加到默认值哈希像这样:

I have also considered adding them to the default hash like so:

class Mailer < ActionMailer::Base
  default ivar: :blah,
  ...
end

唯一的问题是我需要创建这样的方法来检索ivars:

The only problem being that I need to create a method like this to retrieve the ivars:

def default_getter(ivar)
  self.class.default[ivar]
end

对我来说似乎特别干净。我考虑过使用类变量,但是我想知道是否有人可以建议一种更简洁的方法。谢谢。

Neither way seems particularly clean to me. I've considered using class variables, but I'm wondering if someone could suggest a cleaner way. Thanks.

推荐答案

有点迟了...

您可以使用before_action回调

You can use before_action callbacks

http://guides.rubyonrails.org/action_mailer_basics.html#action-mailer-callbacks

这篇关于在Action Mailer中设置实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆