Created
May 3, 2014 20:07
-
-
Save jasonayre/4f57a831468d1198b1ca to your computer and use it in GitHub Desktop.
Rails Dynamic Subdomain Constraint / Store Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
and dont forget | |
config.eager_load_paths << Rails.root.join('lib') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
def current_organization | |
@current_organization ||= ::Subdomains::Organization[request.subdomain] | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Myapp::Application.routes.draw do | |
namespace :api, :constraints => ::Subdomains::Organization do | |
resources :posts | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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