我有一个小组织问题,在我的应用程序中,我有 3 个邮件程序 User_mailer、prduct_mailer、some_other_mailer,它们都将其视图存储在 app/views/user_mailer ...
我希望在 /app/views/ 中有一个名为 mailers 的子目录,并将所有内容放入文件夹 user_mailer、product_mailer 和 some_other_mailer 中。
谢谢,
您确实应该使用默认值创建一个
ApplicationMailer
类,并在邮件程序中继承该类:
# app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
append_view_path Rails.root.join('app', 'views', 'mailers')
default from: "Whatever HQ <[email protected]>"
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>
这个可爱的模式使用与控制器相同的继承方案(例如
ApplicationController < ActionController::Base
)。
我非常同意这个组织策略!
从大雄的例子中,我通过这样做实现了它:
class UserMailer < ActionMailer::Base
default :from => "[email protected]"
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
这是 Mailer 特定的,但还不错!
我在 3.1 中对此有一些运气
class UserMailer < ActionMailer::Base
...
append_view_path("#{Rails.root}/app/views/mailers")
...
end
在 template_root 和 RAILS_ROOT 上收到弃用警告
如果您碰巧需要真正灵活的东西,继承可以帮助您。
class ApplicationMailer < ActionMailer::Base
def self.inherited(subclass)
subclass.default template_path: "mailers/#{subclass.name.to_s.underscore}"
end
end
您可以将模板放在任何您想要的位置,但您必须在邮件中指定它。像这样的东西:
class UserMailer < ActionMailer::Base
default :from => "[email protected]"
def whatever_email(user)
@user = user
@url = "http://whatever.com"
mail(:to => user.email,
:subject => "Welcome to Whatever",
:template_path => '**your_path**',
)
end
end
查看 2.4 邮件视图了解更多信息。
prepend_view_path
中使用
ApplicationMailer
class ApplicationMailer < ActionMailer::Base
layout 'mailer'
prepend_view_path "app/views/mailers" # <---- dump your views here
end
还有什么比这更容易的呢?