I'm trying to write on a module where it can be used on every class regardless of its content:
The module should perform the following:
print the name method and its parameter whenever a method is called.
print the return value of that method.
As an example I got:
class A
extend Loginator
def add(a, b)
a + b
end
def sub(a, b)
a - b
end
logify_me #this where the "logging happens!"
end
a = A.new
a.add(3, 5)
a.sub(7, 4)
output
Methode add(3, 5) called
returns 8
Methode sub(7, 4) called
returns 3
I don't know where to start from. I already read the following links :
So what i did is the following but im kinda stuck:
First try
module Loginator
def logify_me(name)
attr_reader name
define_method("#{name}=") do |val|
puts "#{name}=#{val}"
instance_variable_set("@#{name}", val)
end
end
end
class Example
extend Loginator
logify_me :an_attribute
end
e = Example.new
e.an_attribute = 12
p e.an_attribute
problem with this code is that first i have to strictly write logify_me
for each method and wont print anything if i wrote logify_me
alone
Second try
module Loginator
def logify_me
self.instance_methods.each do |method|
define_method(method) do |*args|
puts "Method #{method}(#{args.join(', ')})"
puts "returns #{args}"
args#problem this return the args not the results of each method?!
end
end
end
end
Note that i could use TracePoint.trace(:call)
but its not what desired :).
Thanks for the user @pedrosfdcarneiro for pointing out the wrapper module solution and providing this ref