Allow rendering different email views per tenant

We were assigning variants in a controller, in the context of a request.
However, when sending emails, there is no request and no controller is
involved, so we also need to set the variant in the ApplicationMailer
class.
This commit is contained in:
Javi Martín
2022-11-28 19:40:50 +01:00
parent 18611f32f1
commit d579bcce2d
2 changed files with 23 additions and 0 deletions

View File

@@ -3,6 +3,7 @@ class ApplicationMailer < ActionMailer::Base
default from: proc { "#{Setting["mailer_from_name"]} <#{Setting["mailer_from_address"]}>" } default from: proc { "#{Setting["mailer_from_name"]} <#{Setting["mailer_from_address"]}>" }
layout "mailer" layout "mailer"
before_action :set_asset_host before_action :set_asset_host
before_action :set_variant
after_action :set_smtp_settings after_action :set_smtp_settings
def default_url_options def default_url_options
@@ -13,6 +14,10 @@ class ApplicationMailer < ActionMailer::Base
self.asset_host ||= root_url.delete_suffix("/") self.asset_host ||= root_url.delete_suffix("/")
end end
def set_variant
lookup_context.variants = [Tenant.current_schema.to_sym]
end
def set_smtp_settings def set_smtp_settings
unless Tenant.default? unless Tenant.default?
mail.delivery_method.settings.merge!(Tenant.current_secrets.smtp_settings.to_h) mail.delivery_method.settings.merge!(Tenant.current_secrets.smtp_settings.to_h)

View File

@@ -78,4 +78,22 @@ describe ApplicationMailer do
end end
end end
end end
describe "#set_variant" do
let(:mailer) { ApplicationMailer.new }
it "uses the default tenant by default" do
mailer.set_variant
expect(mailer.lookup_context.variants).to eq [:public]
end
it "uses the current tenant schema when defined" do
allow(Tenant).to receive(:current_schema).and_return("random-name")
mailer.set_variant
expect(mailer.lookup_context.variants).to eq [:"random-name"]
end
end
end end