用键盘在Ruby中浏览Curses数组

5
我正在尝试用Ruby制作一个cli应用程序,它接受一个给定的数组,然后将其显示为列表,我可以用箭头键浏览。
我感觉已经看到过一个Ruby库已经做到了这一点,但我想不起来它的名字了。
我正在尝试从soundcloud2000的代码中进行反向工程,以做类似的事情,但他的代码与使用Soundcloud API紧密耦合。
我知道curses gem,但我认为需要更多抽象化的东西。
有人看到过做到这一点的库或者能够做到这一点的Ruby概念证明代码吗?
2个回答

6
我不知道这是否是您需要的,但也许您可以使用我的想法。
由于我不知道您想要实现什么,您的输入等信息,所以此示例将非常简单。
假设我们有一个名为PlaylistDemo的类来处理创建带有歌曲的播放列表:
class PlaylistDemo
  attr_accessor :position

  def initialize songs
    @playlist = Array.new
    songs.each { |song| @playlist << song }
    @position = 0
  end

  def show_playlist
    @playlist.each_with_index.map do |song, index|
      position == index ? "[#{song}]" : " #{song} "
    end
  end

end

准备一些歌曲:

# From billboard.com
songs = [
  "Taylor Swift -  Blank Space",
  "Mark Ronson Featuring Bruno Mars -  Uptown Funk!",
  "Hozier -  Take Me To Church",
  "Meghan Trainor - Lips Are Movin",
  "Meghan Trainor -  All About That Bass"
]

接下来可以创建一个对象:

pd = PlaylistDemo.new(songs)

我的想法是使用 dispel 来操作位置,并确切地查看您的位置(并相应地更新“UI”)。

为此,我准备了一个函数,将为您的CLI应用程序创建用户界面:

def show_ui playlist_obj
  ["\n", playlist_obj.show_playlist, "\nCurrent position: #{playlist_obj.position + 1} "].join("\n")
end

最终的代码:

Dispel::Screen.open do |screen|
  screen.draw show_ui(pd)

  Dispel::Keyboard.output do |key|
    case key
    when :up then pd.position -= 1
    when :down then pd.position += 1
    when "q" then break
    end

    screen.draw show_ui(pd)
  end
end

你还可以使用colorize,但需要在某个地方使用puts
请注意,我没有设置位置限制,因为这只是一个示例。
查看我的示例: 完整代码: http://paste.debian.net/139651/

这就是我想要的!Dispel是我想到的库,还有一些完美的示例代码!今晚让我试试,然后给你奖励 :) - Peter Souter
很高兴它有所帮助 :) 这是我的第一个赏金。 - radubogdan

2
你正在寻找 curses ruby gem。
@phoet 创造的菜单 示例
require "curses"
include Curses

init_screen
start_color
noecho

def draw_menu(menu, active_index=nil)
  4.times do |i|
    menu.setpos(i + 1, 1)
    menu.attrset(i == active_index ? A_STANDOUT : A_NORMAL)
    menu.addstr "item_#{i}"
  end
end

def draw_info(menu, text)
  menu.setpos(1, 10)
  menu.attrset(A_NORMAL)
  menu.addstr text
end

position = 0

menu = Window.new(7,40,7,2)
menu.box('|', '-')
draw_menu(menu, position)
while ch = menu.getch
  case ch
  when 'w'
    draw_info menu, 'move up'
    position -= 1
  when 's'
    draw_info menu, 'move down'
    position += 1
  when 'x'
    exit
  end
  position = 3 if position < 0
  position = 0 if position > 3
  draw_menu(menu, position)
end

我知道 curses gem,但我说的是一个更抽象化的库。 - Peter Souter
1
很抱歉这并没有帮到你,下次请说明你已经了解了适用的 gem,这样别人才能更准确地回答你的问题。 - eabraham
没问题,我已经把它加到我的答案里了。 - Peter Souter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接