I know I could define instance variables e.g:
def user_register(username, email)
@username = username
@email = email
mail(:to => email, :subject => "Welcome!", :template_name => "reg_#{I18n.locale}")
end
But, is there a way to use local variables instead, just like passing :locals to partials?
All options available in the
mail
method can be found at http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail.We know that
render
has a:locals
option. However we can see that there is no:locals
option available formail
. Therefore, no, there is no better way than to use instance variables (unless you want to use something hideous like globals or persistent database objects - don't do this).Instance variables are what you are meant to use.
You can actually use the locals option with mail, it's just a bit confusing and inconsistent as to how.
Once you use
:locals
you can then access these locals in the mail template using instance variables, e.g.and then in the template
In Rails 5, you simply have to define instance variables using
@
in your method. You no longer have access to thelocals
property for this purpose.Then you can just access them in your email template using
<%= @user %>
and<%= @token %>
As ronalchn pointed out, it's the
render
that has:locals
, not themail
method. So, you need a direct access to therender
method in order to pass the locals.You can give a block to the
mail
and that way gain access to therender
method, something like this:And now you should be able to use
"Hello <%= recipient_name %>"