Last active
January 2, 2016 04:39
-
-
Save jonathanmarvens/8251475 to your computer and use it in GitHub Desktop.
I've heard many people say that they can't see the usefulness of Ruby 2.0's new `Module#prepend`. IMO, it can be very useful. This is a good example of that.
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
class Hello | |
def world | |
puts 'Hello world!' | |
sleep 1 | |
end | |
end | |
SimpleMethodBenchmark.wrap! Hello, %i{world} | |
hello = Hello.new | |
hello.world |
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
class SimpleMethodBenchmark | |
module Wrapper; end | |
def self.wrap! klass, method_names | |
method_names.each do |method_name| | |
Wrapper.module_eval do | |
define_method method_name do | |
full_method_name = "#{klass.name}##{method_name}" | |
line = ('-' * 35) | |
benchmark_begin = Time.new | |
super() | |
benchmark_end = Time.new | |
benchmark_total = (benchmark_end - benchmark_begin) | |
puts | |
puts ' Method benchmark:' | |
puts " > #{full_method_name}" | |
puts | |
puts line | |
puts " Begin: #{benchmark_begin}" | |
puts " End: #{benchmark_end}" | |
puts " Total: #{(benchmark_total * 1000).round 5} millisecond#{'s' if benchmark_total != 1}" | |
puts line | |
puts | |
end | |
end | |
end | |
klass.class_exec do | |
prepend Wrapper | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment