Created
April 28, 2020 04:30
-
-
Save amirrajan/763241e3191d32b49eeaecc784fcfdf9 to your computer and use it in GitHub Desktop.
trace_module.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Foobar | |
# the extend class macro takes all instance methods and makes them | |
# into class methods | |
extend Foobar | |
# instead of doing self.say_foobar | |
# remove the self, but then "extend" | |
def say_foobar | |
puts "foobar" | |
end | |
end | |
def tick args | |
Tracing.trace_method_for_module! Foobar, :say_foobar | |
Foobar.say_foobar | |
end | |
module Tracing | |
def self.trace_method_for_module! klass, m | |
$already_tracing ||= {} | |
$already_tracing[klass] ||= {} | |
return if $already_tracing[klass][m] | |
klass.module_eval do | |
original_method_name = m | |
trace_method_name = "trace_method_#{Time.now.to_i}" | |
alias_method trace_method_name, m | |
puts "#{m} has been aliased" | |
puts "Tracing #{m} on #{klass}." | |
$already_tracing[klass][m] = true | |
define_method(m) do |*args| | |
parameters = "#{args}"[1..-2] | |
puts "method: #{m}" | |
puts "params: #{parameters}" | |
result = send(trace_method_name, *args) | |
puts "success: #{m}" | |
puts "result: #{result}" | |
puts "nil? #{result.nil?}" | |
result | |
rescue Exception => e | |
puts "failed: #{m}" | |
raise e | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment