A different idea for a monkey patch:
# app/models/action_dispatch_routing_subdomain_extension.rb
module ActionDispatch::Routing
module RouteSetExtensions
# This allows lambdas as subdomain parameter for `default_url_options`:
#
# config.action_mailer.default_url_options = {
# host: 'example.com',
# protocol: 'https',
# subdomain: lambda { ... }
# }
#
def url_for(options, route_name = nil, url_strategy = ActionDispatch::Routing::RouteSet::UNKNOWN)
if options[:subdomain].respond_to? :call
options[:subdomain] = options[:subdomain].call
end
if Rails.application.config.action_mailer.default_url_options[:subdomain].respond_to? :call
options[:subdomain] ||= Rails.application.config.action_mailer.default_url_options[:subdomain].call
end
super(options, route_name, url_strategy)
end
end
class RouteSet
prepend RouteSetExtensions
end
end
Initializer:
# config/initializers/action_dispatch_routing_subdomain_extension.rb
require 'action_dispatch_routing_subdomain_extension'
Then, you can just use a lambda in the subdomain definition:
# config/environments/production.rb
Rails.application.configure do
# ...
config.action_mailer.default_url_options = {
host: 'example.com',
protocol: 'https',
subdomain: lambda { Apartment::Tenant.current }
}
end