Skip to content

Instantly share code, notes, and snippets.

@ouaziz
Created November 2, 2023 18:12
Show Gist options
  • Save ouaziz/7ca144ddfd64f5cca6dd53eeba73d7e6 to your computer and use it in GitHub Desktop.
Save ouaziz/7ca144ddfd64f5cca6dd53eeba73d7e6 to your computer and use it in GitHub Desktop.
# generated by chatgpt
# Configure your config/application.rb to handle subdomains:
# config/application.rb
module YourAppName
class Application < Rails::Application
config.middleware.use SubdomainMiddleware
# ... other configurations
end
end
# Create a custom middleware (SubdomainMiddleware) to handle subdomains and switch tenants based on subdomains. You can create a new file for this middleware, e.g., lib/subdomain_middleware.rb:
# lib/subdomain_middleware.rb
class SubdomainMiddleware
def initialize(app)
@app = app
end
def call(env)
request = ActionDispatch::Request.new(env)
subdomain = request.subdomain
if subdomain.present?
# Implement your logic to determine the tenant based on the subdomain
# You might want to look up the tenant's database configuration in a custom way
# For this example, we'll assume a simple mapping of subdomains to tenant databases
tenant_database = subdomain_to_database(subdomain)
if tenant_database
ENV['TENANT_SUBDOMAIN'] = subdomain
# Switch to the tenant's database
switch_database(tenant_database)
else
# Handle invalid subdomains or show an error page
return [404, { 'Content-Type' => 'text/html' }, ['Invalid subdomain']]
end
end
@app.call(env)
ensure
# Restore the default database connection after the request is processed
ActiveRecord::Base.connection_handler.clear_active_connections!
end
private
def subdomain_to_database(subdomain)
# Implement your logic to map subdomains to tenant databases
# For simplicity, you can use a hash or a database table to store this mapping
# Return the tenant's database name based on the subdomain
end
def switch_database(database)
# Connect to the specified tenant database
ActiveRecord::Base.establish_connection(ActiveRecord::Base.connection_config.merge(database: database))
end
end
# Implement the subdomain_to_database method to map subdomains to tenant databases. You can use a database table or a configuration file to store this mapping.
# Make sure to create separate controllers, views, and logic for the public site and tenant-specific sites as needed.
# database.yml
# config/database.yml
default: &default
adapter: postgresql
encoding: utf8
pool: 5
username: your_db_username
password: your_db_password
host: localhost
development:
<<: *default
database: your_app_development
test:
<<: *default
database: your_app_test
production:
<<: *default
database: your_app_production
<% if ENV['TENANT_SUBDOMAIN'].present? %>
<%= ENV['TENANT_SUBDOMAIN'] %>:
<<: *default
database: <%= ENV['TENANT_SUBDOMAIN'] %>_database
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment