Class: TTY::Prompt::AnswersCollector

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/prompt/answers_collector.rb

Instance Method Summary collapse

Constructor Details

#initialize(prompt, **options) ⇒ AnswersCollector

Initialize answer collector



9
10
11
12
# File 'lib/tty/prompt/answers_collector.rb', line 9

def initialize(prompt, **options)
  @prompt  = prompt
  @answers = options.fetch(:answers) { {} }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, **options, &block) ⇒ Object (private)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



72
73
74
75
# File 'lib/tty/prompt/answers_collector.rb', line 72

def method_missing(method, *args, **options, &block)
  answer = @prompt.public_send(method, *args, **options, &block)
  add_answer(answer)
end

Instance Method Details

#add_answer(answer) ⇒ Object



61
62
63
64
65
66
67
# File 'lib/tty/prompt/answers_collector.rb', line 61

def add_answer(answer)
  if @answers[@name].is_a?(Array)
    @answers[@name] << answer
  else
    @answers[@name] = answer
  end
end

#call(&block) ⇒ Hash

Start gathering answers

Returns:

  • (Hash)

    the collection of all answers



20
21
22
23
# File 'lib/tty/prompt/answers_collector.rb', line 20

def call(&block)
  instance_eval(&block)
  @answers
end

#create_collectorObject



56
57
58
# File 'lib/tty/prompt/answers_collector.rb', line 56

def create_collector
  self.class.new(@prompt)
end

#key(name, &block) ⇒ Object

Create answer entry

Examples:

key(:name).ask("Name?")


31
32
33
34
35
36
37
38
# File 'lib/tty/prompt/answers_collector.rb', line 31

def key(name, &block)
  @name = name
  if block
    answer = create_collector.call(&block)
    add_answer(answer)
  end
  self
end

#values(&block) ⇒ Object

Change to collect all values for a key

Examples:

key(:colors).values.ask("Color?")


46
47
48
49
50
51
52
53
# File 'lib/tty/prompt/answers_collector.rb', line 46

def values(&block)
  @answers[@name] = Array(@answers[@name])
  if block
    answer = create_collector.call(&block)
    add_answer(answer)
  end
  self
end