Created
February 12, 2012 05:09
-
-
Save gruis/1806481 to your computer and use it in GitHub Desktop.
Unblocking the keyboard in EventMachine
This file contains 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
#!/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 | |
} |
This file contains 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
# 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