Class: ListPicker::Picker

Inherits:
Object
  • Object
show all
Defined in:
lib/list_picker.rb

Instance Method Summary collapse

Constructor Details

#initialize(array, options = {}) ⇒ Picker

Returns a new instance of Picker.



6
7
8
9
10
11
12
# File 'lib/list_picker.rb', line 6

def initialize(array, options = {})
@options = {
	label_method: :to_s
	}.merge(options)

	@array = array
end

Instance Method Details

#ask(question, &validation_block) ⇒ Object



14
15
16
17
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
# File 'lib/list_picker.rb', line 14

def ask(question, &validation_block)
			puts ""
			puts "#{question}: "
			puts ""
			@array.each_with_index do |item, index|
				puts "#{(index + 1).to_s.rjust(2)}) #{item.send(@options[:label_method].to_sym)}"
	end
	puts ""
	print "> "

	default_validation_block = Proc.new do |item|
		item.to_i > 0 && item.to_i <= @array.size
	end

	if preselected_option = ARGV.shift
		input = preselected_option
	else
		input = gets.chomp
	end

	unless block_given?
		validation_block = default_validation_block
	end

	unless validation_block.call(input)
		$stderr.puts ""
		$stderr.puts "Invalid selection, please try again"
		return ask(question, &validation_block)
	end

	selected = @array[input.to_i - 1]

	puts ""
	puts "Selected item: #{selected.send(@options[:label_method].to_sym)}"
	puts ""

	return selected
end