Class: Diskman::Chooser
- Inherits:
-
Object
- Object
- Diskman::Chooser
- Defined in:
- lib/diskman/chooser.rb
Overview
Presents the user with a list of items to choose from.
Instance Method Summary collapse
-
#initialize(items, item:) ⇒ Chooser
constructor
A new instance of Chooser.
- #label ⇒ Object
- #select ⇒ Object
Constructor Details
#initialize(items, item:) ⇒ Chooser
Returns a new instance of Chooser.
4 5 6 7 8 |
# File 'lib/diskman/chooser.rb', line 4 def initialize(items, item:) @items = items @singular = item @plural = item + 's' end |
Instance Method Details
#label ⇒ Object
10 11 12 13 14 15 16 |
# File 'lib/diskman/chooser.rb', line 10 def label if @items.length > 1 @plural else @singular end end |
#select ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/diskman/chooser.rb', line 18 def select if @items.length == 0 puts 'No %s found'.yellow % @plural raise Interrupt end if @items.length == 1 puts 'Found the following %s.' % label else puts 'Choose from the following %s.' % @plural end puts @items.each_with_index do |device, i| puts "%6d. %s" % [i + 1, device] end puts if @items.length == 1 puts 'Press enter to select it.' $stdin.gets return @items.first end puts 'Enter your selection.' puts print '> ' selection = $stdin.gets.chomp puts if selection.length == 0 raise Interrupt end selection = selection.to_i if selection <= 0 || selection > @items.length puts 'Invalid selection'.red raise Interrupt end @items[selection - 1] end |