Skip to content

Instantly share code, notes, and snippets.

@Fivell
Forked from vagmi/pg_application_name_patch.rb
Created December 12, 2018 15:57
Show Gist options
  • Save Fivell/e72871f063bf5ec77f9b4c667f7914a8 to your computer and use it in GitHub Desktop.
Save Fivell/e72871f063bf5ec77f9b4c667f7914a8 to your computer and use it in GitHub Desktop.
Set the application name for a postgres connection in Rails 3
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