class IO

Monkey Patch timeout support into the IO class

Public Instance Methods

each_with_timeout(pid, seconds, sep_string=$/) { |buffer| ... } click to toggle source
# File lib/apple_tv_converter/io_patch.rb, line 21
def each_with_timeout(pid, seconds, sep_string=$/)
  sleeping_queue = Queue.new
  thread = nil

  timer_set = lambda do
    thread = new_thread(pid) { AppleTvConverter::Timer.timeout(seconds) { sleeping_queue.pop } }
  end

  timer_cancel = lambda do
    thread.kill if thread rescue nil
  end

  timer_set.call
  each(sep_string) do |buffer|
    timer_cancel.call
    yield buffer
    timer_set.call
  end
ensure
  timer_cancel.call
end

Private Instance Methods

new_thread(pid, &block) click to toggle source
# File lib/apple_tv_converter/io_patch.rb, line 44
def new_thread(pid, &block)
  current_thread = Thread.current
  Thread.new do
    begin
      block.call
    rescue Exception => e
      current_thread.raise e
      if RUBY_PLATFORM =~ /(win|w)(32|64)$/
        Process.kill(1, pid)
      else
        Process.kill('SIGKILL', pid)
      end
    end
  end
end