I have small organizatoric issue, in my application I have 3 mailer User_mailer, prduct_mailer, some_other_mailer and all of them store their views in app/views/user_mailer ...
I will want to have a subdirectory in /app/views/ called mailers and put all in the folders user_mailer, product_mailer and some_other_mailer.
Thanks,
I so agree with this organization strategy!
And from Nobita's example, I achieved it by doing:
class UserMailer < ActionMailer::Base
default :from => "whatever@whatever.com"
default :template_path => '**your_path**'
def whatever_email(user)
@user = user
@url = "http://whatever.com"
mail(:to => user.email,
:subject => "Welcome to Whatever",
)
end
end
It is Mailer-specific but not too bad!
You should really create an ApplicationMailer
class with your defaults and inherit from that in your mailers:
# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
append_view_path Rails.root.join('app', 'views', 'mailers')
default from: "Whatever HQ <hq@whatever.com>"
end
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
def say_hi(user)
# ...
end
end
# app/views/mailers/user_mailer/say_hi.html.erb
<b>Hi @user.name!</b>
This lovely pattern uses the same inheritance scheme as controllers (e.g. ApplicationController < ActionController::Base
).
I had some luck with this in 3.1
class UserMailer < ActionMailer::Base
...
append_view_path("#{Rails.root}/app/views/mailers")
...
end
Got deprecation warnings on template_root and RAILS_ROOT
append_view_path Rails.root.join('app', 'views', 'mailers')
Aliaksandr 2015-04-05 13:38
prepend_view_path
is probably better so the view lookup code doesn't have to look through all other directories before coming to the mailer-only directory to find the template - siannopollo 2018-05-21 02:09
If you happen to need something really flexible, inheritance can help you.
class ApplicationMailer < ActionMailer::Base
def self.inherited(subclass)
subclass.default template_path: "mailers/#{subclass.name.to_s.underscore}"
end
end
You can put the templates wherever you want, but you will have to specify it in the mailer. Something like this:
class UserMailer < ActionMailer::Base
default :from => "whatever@whatever.com"
def whatever_email(user)
@user = user
@url = "http://whatever.com"
mail(:to => user.email,
:subject => "Welcome to Whatever",
:template_path => '**your_path**',
)
end
end
Take a look at 2.4 Mailer Views for more info.
default template_path: "mailers/#{self.name.underscore}"
. In given example, it would look for templates in:/app/views/mailers/user_mailer/
Milovan Zogovic 2014-02-17 09:55