Class: Guardrails::Init::Prompter
- Inherits:
-
Object
- Object
- Guardrails::Init::Prompter
- Defined in:
- lib/guardrails/init/prompter.rb
Overview
Minimal stdin/stdout prompter for guardrails:init. When the input stream isn’t a TTY (CI, piped invocations) every method short-circuits to the configured default — no blocking reads, no surprises.
Instance Method Summary collapse
-
#ask(question, default:) ⇒ Object
Free-text prompt.
-
#choose(question, choices:, default:) ⇒ Object
Choose one of ‘choices` (Strings).
-
#initialize(input: $stdin, output: $stdout) ⇒ Prompter
constructor
A new instance of Prompter.
Constructor Details
#initialize(input: $stdin, output: $stdout) ⇒ Prompter
Returns a new instance of Prompter.
9 10 11 12 |
# File 'lib/guardrails/init/prompter.rb', line 9 def initialize(input: $stdin, output: $stdout) @input = input @output = output end |
Instance Method Details
#ask(question, default:) ⇒ Object
Free-text prompt. Empty input accepts the default.
15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/guardrails/init/prompter.rb', line 15 def ask(question, default:) return default unless interactive? @output.print "#{question} [#{default}]: " @output.flush if @output.respond_to?(:flush) line = @input.gets return default if line.nil? answer = line.chomp.strip answer.empty? ? default : answer end |
#choose(question, choices:, default:) ⇒ Object
Choose one of ‘choices` (Strings). Accepts the choice name itself or its 1-based index. Re-prompts on bad input. Empty input accepts `default`.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/guardrails/init/prompter.rb', line 30 def choose(question, choices:, default:) return default unless interactive? loop do @output.puts question choices.each_with_index do |c, i| marker = c == default ? "*" : " " @output.puts " #{i + 1}) #{c}#{marker == '*' ? ' (default)' : ''}" end @output.print "> " @output.flush if @output.respond_to?(:flush) line = @input.gets return default if line.nil? raw = line.chomp.strip return default if raw.empty? return choices[raw.to_i - 1] if raw.match?(/\A\d+\z/) && (1..choices.length).cover?(raw.to_i) return raw if choices.include?(raw) @output.puts " -> '#{raw}' isn't one of #{choices.join(', ')}; try again." end end |