Sometimes, you want to inject some logic before or after a method invocation. Right, this is one of the typical usage of aspect programming in Java.
But in dynamic language such as Ruby or Python, the language allows you to do this without using any aspect oriented language or tool.
Here is a ruby version, which demonstrates to inject trace message on invocation of methods specified. I also shows the Python version here.
#!/usr/bin/env ruby -w
class Module
private
def trace_it(*ids)
for id in ids
module_eval <<-"end;"
alias_method :__#{id.to_i}__, :#{id.to_s}
private :__#{id.to_i}__
def #{id.to_s}(*args, &block)
puts "[#{Time.now.asctime}] #{name} #{id.to_s} started"
retval = __#{id.to_i}__(*args, &block)
puts "[#{Time.now.asctime}] #{name} #{id.to_s} finished"
return retval
end
end;
end
end
end
class Test1
def foo1()
puts "foo1()"
end
def foo2()
puts "foo2()"
end
end
class Test1
trace_it :foo1, :foo2
end
t1 = Test1.new()
t1.foo2
t1.foo1