Skip to content

Instantly share code, notes, and snippets.

@yaauie
Created April 12, 2021 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaauie/fa72e4d98e7bee771c63fc681793ea44 to your computer and use it in GitHub Desktop.
Save yaauie/fa72e4d98e7bee771c63fc681793ea44 to your computer and use it in GitHub Desktop.
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