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, responseRenderer = nil) ⇒ List

Returns a new instance of List.



55
56
57
58
59
60
61
62
# File 'lib/inquirer/prompts/list.rb', line 55

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

Class Method Details

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



118
119
120
121
# File 'lib/inquirer/prompts/list.rb', line 118

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

Instance Method Details

#run(clear, response) ⇒ 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
response

Bool whether show the rendered response when this is done

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


90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/inquirer/prompts/list.rb', line 90

def run clear, response
  # finish if there's nothing to do
  return nil if Array(@elements).empty?

  # hides the cursor while prompting
  IOHelper.without_cursor do
    # 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
  end

  # clear the final prompt and the line
  IOHelper.clear if clear

  # show the answer
  IOHelper.render( update_response ) if response

  # return the index of the selected item
  @pos
end

#update_promptObject



64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/inquirer/prompts/list.rb', line 64

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

#update_responseObject



77
78
79
# File 'lib/inquirer/prompts/list.rb', line 77

def update_response
  @prompt = @responseRenderer.renderResponse(@question, @elements[@pos])
end