Class: List

Inherits:
Object
  • Object
show all
Defined in:
lib/inquirer/prompts/list.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(question = nil, elements = [], renderer = nil) ⇒ List

Returns a new instance of List.



38
39
40
41
42
43
44
# File 'lib/inquirer/prompts/list.rb', line 38

def initialize question = nil, elements = [], renderer = nil
  @elements = elements
  @question = question
  @pos = 0
  @prompt = ""
  @renderer = renderer || ListDefault.new( Inquirer::Style::Default )
end

Class Method Details

.ask(question = nil, elements = [], opts = { clear: true }) ⇒ Object



84
85
86
87
# File 'lib/inquirer/prompts/list.rb', line 84

def self.ask question = nil, elements = [], opts = { clear: true }
  l = List.new question, elements, opts[:renderer]
  l.run opts[:clear]
end

Instance Method Details

#run(clear = true) ⇒ Object

Run the list selection, wait for the user to select an item and return the selected index Params:

clear

Bool whether to clear the selection prompt once this is done

defaults to true; set it to false if you want the prompt to remain after
the user is done with selecting


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/inquirer/prompts/list.rb', line 65

def run clear = true
  # finish if there's nothing to do
  return nil if Array(@elements).empty?
  # render the
  IOHelper.render( update_prompt )
  # loop through user input
  IOHelper.read_key_while do |key|
    @pos = (@pos - 1) % @elements.length if key == "up"
    @pos = (@pos + 1) % @elements.length if key == "down"
    IOHelper.rerender( update_prompt )
    # we are done if the user hits return
    key != "return"
  end
  # clear the final prompt and the line
  IOHelper.clear if clear
  # return the index of the selected item
  @pos
end

#update_promptObject



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/inquirer/prompts/list.rb', line 46

def update_prompt
  # transform the list into
  # {"value"=>..., "selected"=> true|false}
  e = @elements.
    # attach the array position
    map.with_index(0).
    map do |c,pos|
      { "value"=>c, "selected" => pos == @pos }
    end
  # call the renderer
  @prompt = @renderer.render(@question, e)
end