Skip to content

Instantly share code, notes, and snippets.

@robhurring
Created September 25, 2015 22:00
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 robhurring/3a5c55c7549d25b10925 to your computer and use it in GitHub Desktop.
Save robhurring/3a5c55c7549d25b10925 to your computer and use it in GitHub Desktop.
Ruby decorators
require 'byebug'
require 'benchmark'
require 'timeout'
module Decorator
def decorate(method, &block)
decorator = Module.new do
define_method(method, &block)
end
prepend(decorator)
method
end
def registry
@_registry ||= ObjectSpace::WeakMap.new
@_registry[self] ||= []
end
def decorator(&block)
registry << block
end
def method_added(method)
registry.each do |wrapper|
decorate(method, &wrapper)
end
registry.clear
end
end
module Profiling
include Decorator
def timeout(n)
decorator do
begin
Timeout.timeout(n){ super() }
rescue Timeout::Error
puts "Timed out!"
nil
end
end
end
def benchmark
decorator do
Benchmark.bm do |bm|
bm.report(__method__){ super() }
end
end
end
end
class Thyme
extend Profiling
benchmark
timeout(3)
def now(ohai = true)
sleep 4
Time.now
end
def hey
"help!"
end
end
thyme = Thyme.new
puts thyme.now
puts thyme.hey
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment