Setting instance variables in Action Mailer?

2019-05-08 21:35发布

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

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

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.

1条回答
smile是对你的礼貌
2楼-- · 2019-05-08 22:02

Just a little bit late...

You can use before_action callbacks

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

查看更多
登录 后发表回答