Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting instance variables in Action Mailer?

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.

like image 554
RubeOnRails Avatar asked Oct 07 '13 23:10

RubeOnRails


People also ask

What is action mailer?

Action Mailer allows you to send emails using mailer classes and views. Mailers work very similarly to controllers.

What is instance variable in Ruby on Rails?

An instance variable in ruby has a name starting with @ symbol, and its content is restricted to whatever the object itself refers to. Two separate objects, even though they belong to the same class, are allowed to have different values for their instance variables.

How do I send an email to ROR?

Go to the config folder of your emails project and open environment. rb file and add the following line at the bottom of this file. It tells ActionMailer that you want to use the SMTP server. You can also set it to be :sendmail if you are using a Unix-based operating system such as Mac OS X or Linux.


1 Answers

Just a little bit late...

You can use before_action callbacks

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

like image 62
Daniel Avatar answered Oct 20 '22 07:10

Daniel