2

I have around 30 mailer methods where I'm passing the user as an argument. Since I need access to the @user variable in the view, I'm having to set this instance variable in every mailer method, for example, send_x_email(user).

Normally this would be done in an initialize method, but I've read that mailers act a bit differently. Additionally, some of the methods take a different number of arguments (one just takes user, the other takes user and message).

I've investigated before_action callbacks and looked at this post

Setting instance variables in Action Mailer?

...but I'm still stuck.

I would appreciate any thoughts on how to simplify things and remove @user = user from the 30 or so methods in the mailer class. Cheers!

class ReminderSender < ActionMailer::Base
  def send_commands_email(user)
    @user = user
    mail(to: @user.email,
         subject: "All Commands",
         from: "<commands@#{ENV['DOMAIN']}>")
  end

  def send_attachment_warning(user, message)
    @user = user
    @message = message
    mail(to: @user.email,
         subject: "Attachment Warning",
         from: "<attachments@#{ENV['DOMAIN']}>")
  end
end

1 Answer 1

2

Try defining a 'mail' method in your class and declaring an instance variable there e.g.

class YouMailer

  def send_email(user, message)
    subject = 'something'
    body = message

    mail(user, {subject: subject, body: body}})
  end

  def mail(user, options={})
    @user = user
    mail_options = {to: @user.email}.merge(options)

    super(mail_options)
  end
end

But you might need to specify the 'template_path' and 'template_name' options with that strategy.

My suggestion would be to keep things as they are. Having "@user = user" in all of your mailer methods out of necessity isn't bad.

1
  • Agree re: setting @user in all the methods. You can actually think of mailer methods as analogous to controller actions. In a controller action you don't think twice about setting instance variables for each method, because you know that a new controller instance is created for each request and exactly one action is ever called.
    – jjm
    Dec 17, 2014 at 0:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.