Consider the current tenant in email URLs

This commit is contained in:
Javi Martín
2022-09-24 15:14:12 +02:00
parent 5983006657
commit 275ddb08d8
3 changed files with 66 additions and 0 deletions

View File

@@ -6,7 +6,25 @@ class ApplicationMailer < ActionMailer::Base
layout "mailer"
before_action :set_asset_host
def default_url_options
if Tenant.default?
super
else
super.merge(host: host_with_subdomain_for(super[:host]))
end
end
def set_asset_host
self.asset_host ||= root_url.delete_suffix("/")
end
private
def host_with_subdomain_for(host)
if host == "localhost"
"#{Tenant.current_schema}.lvh.me"
else
"#{Tenant.current_schema}.#{host}"
end
end
end

View File

@@ -31,6 +31,14 @@ class Tenant < ApplicationRecord
ActionMailer::Base.default_url_options[:host]
end
def self.current_schema
Apartment::Tenant.current
end
def self.default?
current_schema == "public"
end
def self.switch(...)
Apartment::Tenant.switch(...)
end

View File

@@ -1,6 +1,28 @@
require "rails_helper"
describe ApplicationMailer do
describe "#default_url_options" do
it "returns the same options on the default tenant" do
allow(ActionMailer::Base).to receive(:default_url_options).and_return({ host: "consul.dev" })
expect(ApplicationMailer.new.default_url_options).to eq({ host: "consul.dev" })
end
it "returns the host with a subdomain on other tenants" do
allow(ActionMailer::Base).to receive(:default_url_options).and_return({ host: "consul.dev" })
allow(Tenant).to receive(:current_schema).and_return("my")
expect(ApplicationMailer.new.default_url_options).to eq({ host: "my.consul.dev" })
end
it "uses lvh.me for subdomains when the host is localhost" do
allow(ActionMailer::Base).to receive(:default_url_options).and_return({ host: "localhost", port: 3000 })
allow(Tenant).to receive(:current_schema).and_return("dev")
expect(ApplicationMailer.new.default_url_options).to eq({ host: "dev.lvh.me", port: 3000 })
end
end
describe "#set_asset_host" do
let(:mailer) { ApplicationMailer.new }
@@ -24,6 +46,24 @@ describe ApplicationMailer do
expect(mailer.asset_host).to eq "https://localhost:3000"
end
it "returns the host with a subdomain on other tenants" do
allow(ActionMailer::Base).to receive(:default_url_options).and_return(host: "consul.dev")
allow(Tenant).to receive(:current_schema).and_return("my")
mailer.set_asset_host
expect(mailer.asset_host).to eq "http://my.consul.dev"
end
it "uses lvh.me for subdomains when the host is localhost" do
allow(ActionMailer::Base).to receive(:default_url_options).and_return(host: "localhost", port: 3000)
allow(Tenant).to receive(:current_schema).and_return("dev")
mailer.set_asset_host
expect(mailer.asset_host).to eq "http://dev.lvh.me:3000"
end
it "returns the asset host when set manually" do
default_asset_host = ActionMailer::Base.asset_host