Method: Lowline#ask

Defined in:
lib/lowline.rb

#ask(q, opts = {}) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/lowline.rb', line 71

def ask q, opts={}
  default_s = case opts[:default]
    when nil; nil
    when ""; " (enter for none)"
    else; " (enter for #{opts[:default].inspect})"
  end

  tail = case q
    when /[:?]$/; " "
    when /[:?]\s+$/; ""
    else; ": "
  end

  while true
    print [q, default_s, tail].compact.join
    ans = gets.strip
    if opts[:default]
      ans = opts[:default] if ans.blank?
    else
      next if ans.blank? && !opts[:empty_ok]
    end
    break ans unless (opts[:restrict] && ans !~ opts[:restrict])
  end
end