From 409ed6065567bb929047e1e7777754065b37cbf3 Mon Sep 17 00:00:00 2001 From: Stephen Margheim Date: Tue, 8 Oct 2024 16:17:32 +0200 Subject: [PATCH] Allow users to specify a new for form fields The response object from Form.submit is a hash that uses either provided names of incrementing integers (1-indexed) Resolves #7. --- lib/prompts/form.rb | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/lib/prompts/form.rb b/lib/prompts/form.rb index 91257b8..49848ba 100644 --- a/lib/prompts/form.rb +++ b/lib/prompts/form.rb @@ -10,8 +10,9 @@ def self.submit(&block) def initialize @content = Prompts::Content.new - @prompts = [] - @results = [] + @index = 0 + @prompts = {} + @results = {} end def content(&block) @@ -19,37 +20,41 @@ def content(&block) @content end - def text(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil, &block) + def text(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil, name: nil, &block) prompt = TextPrompt.new(label: label, prompt: prompt, hint: hint, default: default, required: required, validate: validate) yield(prompt) if block prepend_form_content_to_prompt(prompt) - @prompts << prompt + key = name || (@index += 1) + @prompts[key] = prompt end - def select(label: nil, options: nil, prompt: "> ", hint: nil, default: nil, validate: nil, &block) + def select(label: nil, options: nil, prompt: "> ", hint: nil, default: nil, validate: nil, name: nil, &block) prompt = SelectPrompt.new(label: label, options: options, prompt: prompt, hint: hint, default: default, validate: validate) yield(prompt) if block prepend_form_content_to_prompt(prompt) - @prompts << prompt + key = name || (@index += 1) + @prompts[key] = prompt end - def pause(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil, &block) + def pause(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil, name: nil, &block) prompt = PausePrompt.new(label: label, prompt: prompt, hint: hint, default: default, required: required, validate: validate) yield(prompt) if block prepend_form_content_to_prompt(prompt) - @prompts << prompt + key = name || (@index += 1) + @prompts[key] = prompt end - def confirm(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil, &block) + def confirm(label: nil, prompt: "> ", hint: nil, default: nil, required: false, validate: nil, name: nil, &block) prompt = ConfirmPrompt.new(label: label, prompt: prompt, hint: hint, default: default, required: required, validate: validate) yield(prompt) if block prepend_form_content_to_prompt(prompt) - @prompts << prompt + key = name || (@index += 1) + @prompts[key] = prompt end def submit - @prompts.each do |prompt| - @results << prompt.ask + @prompts.each do |key, prompt| + @results[key] = prompt.ask end @results end