RSS

tumble.lukeredpath

Sep 23
Permalink

Timeout on any Ruby method


require 'timeout'

class TimeoutProxy
  include Timeout
  
  def initialize(receiver, timeout_in_seconds)
    @receiver = receiver
    @timeout_in_seconds = timeout_in_seconds
  end
  
  def method_missing(method, *args, &block)
    timeout(@timeout_in_seconds) do
      @receiver.send(method, *args, &block)
    end
  end
end

class Object
  def with_timeout(timeout_in_seconds)
    TimeoutProxy.new(self, timeout_in_seconds)
  end
end

# EXAMPLE:
#  class Foo
#    def self.some_long_running_method
#      sleep 10; puts 'done';
#    end
#  end
#
#  # without timeout
#  Foo.some_long_running_method
#  #=> 'done'
#
#  # with timeout
#  Foo.with_timeout(3).long_running_method
#  #=> raises Timeout::Error