2013-05-13 14 views
2

我一直在互聯網尋找這個答案一段時間,並發現其他人問同樣的事情,即使在這裏。所以這篇文章將介紹我的案例和對我找到的「解決方案」的迴應。在Ruby控制檯應用程序中獲取鍵盤事件(輸入時沒有按'輸入')的最佳方式是什麼?

我在Ruby中很新,但爲了學習的目的,我決定創建一個gem,here。 我正試圖實現一個鍵盤導航到這個程序,這將允許用戶使用快捷方式來選擇他想要看什麼樣的請求。並在未來,箭頭導航等

我的問題:我找不到一致的方式從用戶的控制檯與Ruby獲取鍵盤事件。

的解決方案,我曾嘗試:

  1. 海萊寶石:似乎不支持此功能了。無論如何,它使用STDIN,繼續閱讀。
  2. STDIN.getch:我需要在並行循環中運行它,因爲同時用戶可以使用快捷方式,可以創建更多數據並且程序需要顯示它。還有,我在控制檯中顯示格式化文本(Rails日誌)。當這個循環運行時,我的文本丟失了所有的格式。
  3. Curses:酷,但我需要設置位置(x,y)每次顯示我的文本?它會變得混亂。

Here是我試圖去做的地方。 您可能會注意到,我在顯示我的文本之前使用了「stty -raw echo」(關閉原始狀態),之後使用了「stty raw -echo」(開啓了原始狀態)。這使我的文本格式化。

但我的關鍵聽衆循環無法正常工作。我的意思是,它有時有效但不一致。如果按兩次按鍵,則不再有效,有時也會單獨停止。

讓我把這裏的代碼的一部分:

def run 
    # Two loops run in parallel using Threads. 
    # stream_log loops like a normal stream in the file, but it also parser the text. 
    # break it into requests and store in @requests_queue. 
    # stream_parsed_log stream inside the @requests_queue and shows it in the 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 do 
     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 

我需要一個光在我的道路,我該怎麼辦?

回答

0

那是我的錯。 這只是在另一個線程中運行的代碼的另一部分的邏輯錯誤,所以紅寶石默認情況下不顯示錯誤。我使用ruby -d並意識到錯誤。這個錯誤搞亂了我的鍵盤輸入。

所以現在它是固定的,我正在使用STDIN.getch沒有問題。 我只是在顯示任何字符串之前關閉原始模式。一切都好。

您可以檢查heregem本身。

就是這樣。

相關問題