Skip to content

Instantly share code, notes, and snippets.

@gruis
Created February 12, 2012 05:09
Show Gist options
  • Save gruis/1806481 to your computer and use it in GitHub Desktop.
Save gruis/1806481 to your computer and use it in GitHub Desktop.
Unblocking the keyboard in EventMachine
#!/usr/bin/env ruby -wW1
require File.expand_path("../nb-keyboard", __FILE__)
EM.run {
spinner = EventMachine::PeriodicTimer.new(0.5) do
$stderr.print "."
end
Fiber.new {
EM.open_keyboard(NbKeyboard) do |kb|
inp = Readline.readline("enter something ")
$stderr.puts "you entered: #{inp.inspect}"
EM::Timer.new(0.75) { EM.stop }
end
}.resume
}
# doesn't work with Stdlib Readline
require 'rb-readline'
require 'fiber'
require 'eventmachine'
module NbKeyboard
def post_init
@ostdin = $stdin
$stdin = self
@buffer = ""
end
def receive_data(d)
@buffer << d
@waiting && @waiting[:cnt] <= @buffer.length && @waiting[:fiber].resume
end
def read(cnt)
if @buffer.length < cnt
@waiting = {:cnt => cnt, :fiber => Fiber.current}
Fiber.yield
end
data, @buffer = @buffer[0...cnt], @buffer[cnt..-1]
data
end
def unbind
$stdin = @ostdin
end
def method_missing(meth, *args, &blk)
@ostdin.send(meth, *args, &blk)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment