io - What is the best way to get keyboard events (input without press 'enter') in a Ruby console application? -
i've been looking answer in internet while , have found other people asking same thing, here. post presentation of case , response "solutions" have found.
i such new in ruby, learning purposes decided create gem, here. trying implement keyboard navigation program, allow user use short-cuts select kind of request want see. , in future, arrow navigations, etc.
my problem: can't find consistent way keyboard events user's console ruby.
solutions have tried:
- highline gem: seems not support feature anymore. anyway uses stdin, keep reading.
- stdin.getch: need run in parallel loop, because @ same time user can use short-cut, more data can created , program needs show it. , well, display formated text in console, (rails log). when loop running, text lost format.
- curses: cool need set position(x,y) display text every time? confusing.
here trying it. may note using "stty -raw echo" (turns raw off) before show text , "stty raw -echo" (turns raw on) after. keeps text formated.
but key listener loop not working. mean, works in not consistent. if press key twice don't work anymore , stops alone too.
let me put 1 part of code here:
def run # 2 loops run in parallel using threads. # stream_log loops normal stream in file, parser text. # break requests , store in @requests_queue. # stream_parsed_log stream inside @requests_queue , shows in screen. @requests_queue = queue.new @all_requests = array.new # it's not working yet. thread.new { listen_keyboard } thread.new { stream_log } stream_parsed_log end def listen_keyboard # not finished loop char = stdin.getch case char when 'q' puts "exiting." exit when 'a' @types_to_show = ['get', 'post', 'put', 'delete', 'asset'] requests_to_show = filter_to_show(@all_requests) command = true when 'p' @types_to_show = ['post'] requests_to_show = filter_to_show(@all_requests) command = true end clear_screen if command @requests_queue += requests_to_show if command command = false end end
i need light in path, should do?
that 1 mistake. it's logic error in part of code running in thread ruby don't shows error default. used ruby -d , realized wrong. mistake messing keyboard input.
so it's fixed , using stdin.getch no problem. turn raw mode off before show string. , ok.
you can check here, or in gem itself.
that's it.
Comments
Post a Comment