Skip to content

Instantly share code, notes, and snippets.

@jasonayre
Created May 3, 2014 20:07
Show Gist options
  • Save jasonayre/4f57a831468d1198b1ca to your computer and use it in GitHub Desktop.
Save jasonayre/4f57a831468d1198b1ca 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