Login
console.cr at tip
Login

File src/remilib/console/console.cr from the latest check-in


     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
#### libremiliacr
#### Copyright(C) 2020-2024 Remilia Scarlet <remilia@posteo.jp>
####
#### This program is free software: you can redistribute it and/or modify
#### it under the terms of the GNU General Public License as published
#### the Free Software Foundation, either version 3 of the License, or
#### (at your option) any later version.
####
#### This program is distributed in the hope that it will be useful,
#### but WITHOUT ANY WARRANTY; without even the implied warranty of
#### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
#### GNU General Public License for more details.
####
#### You should have received a copy of the GNU General Public License
#### along with this program.If not, see<http:####www.gnu.org/licenses/.>

# The `RemiLib::Console` module provides various terminal-related functionality.
module RemiLib::Console
  # Prints `question`, then waits for the user to respond.  If `needFull` is
  # true, then the user must respond with the full words `yes` or `no`.  If
  # `needFull` is false (the default), then they can respond with `y`, `yes`,
  # `n`, or `no`.
  #
  # This returns true if the user responded in the affirmitive, or false
  # otherwise.
  def self.askYesNo(question : String, needFull : Bool = false, *, input : IO = STDIN, output : IO = STDOUT) : Bool
    loop do
      output << "#{question} " << (needFull ? "(yes/no)" : "(y/n)") << ": "
      line = (input.gets || "").downcase

      if needFull
        case line
        when "yes" then return true
        when "no" then return false
        else output << "Please answer 'yes' or 'no'\n"
        end
      else
        case line
        when "yes", "y" then return true
        when "no", "n" then return false
        else output << "Please answer 'y' or 'n'\n"
        end
      end
    end
  end
end