Skip to content

Instantly share code, notes, and snippets.

@spickermann
Created January 2, 2013 09:05
Show Gist options
  • Save spickermann/4433184 to your computer and use it in GitHub Desktop.
Save spickermann/4433184 to your computer and use it in GitHub Desktop.
module ModelExt
module MasterSlaveDb
# This module allows you to send db queries directly to the slave database.
# Please do not use this on the user frontend at the moment - administration interface only.
#
# 1) The slave is weaker (CPU, RAM) than the master.
# 2) The slave will be down around lunch time for backup reasons.
#
# Usage:
# include ModelExt::MasterSlaveDb
#
# Model.with_slave_db! do
# Model.slow_find
# end
#
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def with_slave_db!
connect_with!(:slave)
yield
ensure
connect_with!(:master)
end
private
def connect_with!(type)
if Rails.env.development?
called_by = caller(2).first rescue "unknown"
::Rails.logger.debug("DB SWITCH -------------------------------------------")
::Rails.logger.debug("BY #{ called_by.gsub(Rails.root, '') }")
::Rails.logger.debug("TO #{ type }")
::Rails.logger.debug("-----------------------------------------------------")
end
clear_all_connections! # Returns connections back to the pool
case type
when :master then establish_connection(configurations[Rails.env])
when :slave then establish_connection(YamlLoader.file('database_slave').marshal_dump)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment