Skip to content

Instantly share code, notes, and snippets.

@aprescott
Created March 26, 2014 15:04
Show Gist options
  • Save aprescott/9785441 to your computer and use it in GitHub Desktop.
Save aprescott/9785441 to your computer and use it in GitHub Desktop.
Slow down an instance method by 1 second.
# Delay Foo#method by 1 second before
# executing its original implementation.
def delay_method(klass, method)
sleeping_giant = Module.new do
define_method(method) do |*args, &block|
sleep 1
super(*args, &block)
end
end
klass.prepend(sleeping_giant)
yield
sleeping_giant.module_eval do
remove_method method
end
end
# class X
# def foo
# p(:x)
# end
# end
#
# X.new.foo # fast
#
# delay_method(X, :foo) do
# X.new.foo # slow
# end
#
# X.new.foo # fast again
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment