ActiveRecord Connection : Custom initializer
I would like to execute a simple sql line each time a new connection is made (on that same connection)
Why? Using postgres, "set application_name = 'abc';" will allow me to keep track of the application using the connections when I query my database server for stats.
开发者_运维技巧Haven't seen anything that would allow me to do this.
I solved a similar problem recently. I was changing the transaction isolation level after connecting. This example should help you out. It is based on the advice in the final example on this blog post.
# lib/active_record/application_name.rb
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)
::ActiveRecord::Base.connection.execute("set application_name = 'abc';")
result
end
end
end
end
# lib/patches/active_record.rb
require 'active_record/application_name'
class ActiveRecord::Base
include ActiveRecord::ApplicationName
end
# config/initializers/patches.rb
require 'patches/active_record'
精彩评论