Wrapping class method

Hey guys, I’m having trouble figuring out how to wrap a class method. I
want to add a logger.debug to ActiveRecord::Base.establish_connection,
just trying to figure out how the rails database connection lifecycle is
supposed to work. I tried this naive approach:

module ActiveRecord

class Base

alias self.old_establish_connection self.establish_connection

def self.establish_connection(arg)
  logger.debug("Establishing connection")
  self.old_establish_connection(arg)
end

end

end

of course, ruby doesn’t like this, the self.old_establish_connection bit
throws a SyntaxError. How ought I go about doing this?

  • donald

Hey guys, I’m having trouble figuring out how to wrap a class
method.

Wrapping methods? That good old story? Have a look at [1]… ;]

gegroet,
Erik V. - http://www.erikveen.dds.nl/

[1] Ruby Monitor-Functions - Or Meta-Meta-Programming in Ruby


$ cat init.rb
require “ev/metameta” # This is where I store my
meta-meta-programming stuff.

require “rubygems”
require “active_record”

module ActiveRecord
class Base
metaclass.pre_condition(:establish_connection) do |obj,
method_name, args, block|
puts “Establishing connection”
end
end
end

load “script/server”

On Wed, 2007-01-24 at 04:14 +0900, Ball, Donald A Jr (Library) wrote:

throws a SyntaxError. How ought I go about doing this?

  • donald

Try this:

module ActiveRecord

class Base

class << self
  alias old_establish_connection establish_connection
end

def self.establish_connection(arg)
  logger.debug("Establishing connection")
  self.old_establish_connection(arg)
end

end
end

Another approach might be to use super like this:

module ActiveRecord
class Base
def self.establish_connection(arg)
logger.debug(“Establishing connection”)
super arg
end
end
end