lib/tty/prompt/question.rb in tty-prompt-0.18.1 vs lib/tty/prompt/question.rb in tty-prompt-0.19.0

- old
+ new

@@ -32,11 +32,11 @@ attr_reader :validation # Initialize a Question # # @api public - def initialize(prompt, options = {}) + def initialize(prompt, **options) @prompt = prompt @prefix = options.fetch(:prefix) { @prompt.prefix } @default = options.fetch(:default) { UndefinedSetting } @required = options.fetch(:required) { false } @echo = options.fetch(:echo) { true } @@ -45,12 +45,14 @@ @validation = options.fetch(:validation) { UndefinedSetting } @convert = options.fetch(:convert) { UndefinedSetting } @active_color = options.fetch(:active_color) { @prompt.active_color } @help_color = options.fetch(:help_color) { @prompt.help_color } @error_color = options.fetch(:error_color) { :red } + @value = options.fetch(:value) { UndefinedSetting } @messages = Utils.deep_copy(options.fetch(:messages) { { } }) @done = false + @first_render = true @input = nil @evaluator = Evaluator.new(self) @evaluator << CheckRequired @@ -92,12 +94,11 @@ # @param [String] message # # @return [self] # # @api public - def call(message, &block) - return if Utils.blank?(message) + def call(message = '', &block) @message = message block.call(self) if block @prompt.subscribe(self) do render end @@ -129,11 +130,14 @@ # # @return [String] # # @api private def render_question - header = ["#{@prefix}#{message} "] + header = [] + if !Utils.blank?(@prefix) || !Utils.blank?(message) + header << "#{@prefix}#{message} " + end if !echo? header elsif @done header << @prompt.decorate(@input.to_s, @active_color) elsif default? && !Utils.blank?(@default) @@ -156,11 +160,16 @@ # Process input # # @api private def read_input(question) - @prompt.read_line(question, echo: echo).chomp + options = {echo: echo} + if value? && @first_render + options[:value] = @value + @first_render = false + end + @prompt.read_line(question, options).chomp end # Handle error condition # # @return [String] @@ -262,9 +271,24 @@ # # @api public def validate(value = nil, message = nil, &block) messages[:valid?] = message if message @validation = (value || block) + end + + # Prepopulate input with custom content + # + # @api public + def value(val) + return @value if val.nil? + @value = val + end + + # Check if custom value is present + # + # @api private + def value? + @value != UndefinedSetting end def validation? @validation != UndefinedSetting end