Skip to content

Instantly share code, notes, and snippets.

@kohheepeace
Forked from jasonayre/application.rb
Created August 15, 2021 21:05
Show Gist options
  • Save kohheepeace/520a7ca7d83c24f51e38af3ea77356da to your computer and use it in GitHub Desktop.
Save kohheepeace/520a7ca7d83c24f51e38af3ea77356da to your computer and use it in GitHub Desktop.
Rails Dynamic Subdomain Constraint / Store Example
and dont forget
config.eager_load_paths << Rails.root.join('lib')
class ApplicationController < ActionController::Base
def current_organization
@current_organization ||= ::Subdomains::Organization[request.subdomain]
end
end
Myapp::Application.routes.draw do
namespace :api, :constraints => ::Subdomains::Organization do
resources :posts
end
end
#put in lib and eager load
module Subdomains
class Organization
class << self
attr_accessor :subdomains
end
def self.loaded_subdomains
return unless load_subdomains?
@loaded_subdomains ||= ::Organization.by_active.inject({}) do |hash, organization|
hash[organization.subdomain] = organization
hash
end
end
def self.load_subdomains?
::ActiveRecord::Base.connection.table_exists?("organizations")
end
@subdomains ||= loaded_subdomains
def self.matches?(request)
subdomains.include?(request.subdomain)
end
def self.[](key)
subdomains[key]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment