Setting instance variables in Action Mailer?

╄→гoц情女王★ 提交于 2019-12-07 06:27:19

问题


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:


Just a little bit late...

You can use before_action callbacks

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



来源:https://stackoverflow.com/questions/19236674/setting-instance-variables-in-action-mailer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!