Skip to content

Instantly share code, notes, and snippets.

@amirrajan
Created April 28, 2020 04:30
Show Gist options
  • Save amirrajan/763241e3191d32b49eeaecc784fcfdf9 to your computer and use it in GitHub Desktop.
Save amirrajan/763241e3191d32b49eeaecc784fcfdf9 to your computer and use it in GitHub Desktop.
trace_module.rb
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