Created
April 12, 2021 17:03
-
-
Save yaauie/fa72e4d98e7bee771c63fc681793ea44 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'time' # Time#iso8601 | |
# A NoisyProxy will log all method calls on the wrapped object and their results to the given IO. | |
# It will optionally _infect_ any object returned by the real method. | |
class NoisyProxy < BasicObject | |
def initialize(inner, infect:false, io:$stderr) | |
@inner = inner | |
@infect = infect | |
@io = io | |
end | |
def method_missing(method_name, *arguments, &block) | |
start = ::Time.now | |
@io.write "[#{start.iso8601(9)}] (#{@inner})\##{method_name}(#{arguments.map(&:inspect).join(',')})" | |
@io.write '{ ... }' unless block.nil? | |
result = @inner.send(method_name, *arguments, &block) | |
@io.puts(" #=> #{result} (#{(::Time.now - start).truncate(9)}s)" ) | |
@infect ? NoisyProxy.new(result, io: @io, infect: @infect) : result | |
rescue => e | |
@io.puts(" #!> #{e}") | |
raise | |
end | |
def respond_to_missing?(m) | |
@inner.respond_to?(m) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment