Created
May 11, 2012 06:13
-
-
Save vagmi/2657867 to your computer and use it in GitHub Desktop.
Set the application name for a postgres connection in Rails 3
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
module ActiveRecord | |
module ApplicationName | |
def self.included(base) | |
unless base.respond_to? :establish_connection_with_application_name | |
base.extend ClassMethods | |
base.class_eval do | |
class << self | |
alias_method_chain :establish_connection, :application_name | |
end | |
end | |
end | |
end | |
module ClassMethods | |
def establish_connection_with_application_name(*args) | |
result = establish_connection_without_application_name(*args) | |
appname = Rails.application.class.name.split('::')[0].tableize rescue 'rails' | |
appname = "#{appname}_without_pool" | |
::ActiveRecord::Base.connection.execute("set application_name = '#{appname}';") | |
result | |
end | |
end | |
end | |
module PoolApplicationName | |
def self.included(base) | |
unless base.respond_to? :new_connection_with_application_name | |
base.class_eval do | |
include InstanceMethods | |
alias_method_chain :new_connection, :application_name | |
end | |
end | |
end | |
module InstanceMethods | |
def new_connection_with_application_name(*args) | |
result = new_connection_without_application_name(*args) | |
appname = Rails.application.class.name.split('::')[0].tableize rescue 'rails' | |
@pool_number ||= 1 | |
appname = "#{appname}_with_pool_#{@pool_number}" | |
result.execute("set application_name = '#{appname}';") | |
@pool_number = @pool_number + 1 | |
result | |
end | |
end | |
end | |
end | |
class ActiveRecord::Base | |
include ActiveRecord::ApplicationName | |
end | |
class ActiveRecord::ConnectionAdapters::ConnectionPool | |
include ActiveRecord::PoolApplicationName | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment