Created
May 21, 2009 22:40
-
-
Save brandon-beacher/115793 to your computer and use it in GitHub Desktop.
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 DomainMiddleware | |
@@connection_handlers = {} | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
@request = ActionController::Request.new(env) | |
env["rack.session.options"][:domain] = @request.stage_and_domain | |
@default_handler = ActiveRecord::Base.connection_handler | |
environment = ActiveRecord::Base.connection.select_value("select environment from domains where name = '#{@request.stage_and_domain}'") | |
raise ActiveRecord::RecordNotFound, "Unable to find domain '#{@request.stage_and_domain}' at Digital Faith" if environment.blank? | |
raise ActiveRecord::RecordNotFound, "Mismatched stage '#{@request.stage}' for environment '#{Dfc.base_env}' at Digital Faith" if @request.mismatched_stage? | |
domain_handler = @@connection_handlers[@request.stage_and_domain] | |
if domain_handler | |
ActiveRecord::Base.connection_handler = domain_handler | |
else | |
ActiveRecord::Base.connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new | |
ActiveRecord::Base.establish_connection(environment) | |
@@connection_handlers[@request.stage_and_domain] = ActiveRecord::Base.connection_handler | |
end | |
@app.call(env) | |
ensure | |
ActiveRecord::Base.connection_handler = @default_handler | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment