Below is code for a class that can dynamically add logging to a method. This works in the case where the method takes no parameters and accepts no block.
How can I rewrite the code, so that I can add logging of a method even if it accepts parameters and accepts a block?
class X
def greet
puts "hi"
end
def self.add_logging(method_name)
alias_method("original_#{method_name}".to_sym, method_name)
#How do i rewrie this to account for method_name's arguments and ability to accept a block?
define_method(method_name) do
puts "calling #{method_name}"
send "original_#{method_name}".to_sym
puts "done #{method_name}"
end
end
end
x = X.new
x.greet
X.add_logging(:greet)
x.greet
outputs
>hi
>calling greet
>hi
>done greet
will give: