Skip to content

Instantly share code, notes, and snippets.

@RespiteSage
Created January 21, 2022 22:47
Show Gist options
  • Save RespiteSage/75cfe6eb1cb65bf8ac551ec925238246 to your computer and use it in GitHub Desktop.
Save RespiteSage/75cfe6eb1cb65bf8ac551ec925238246 to your computer and use it in GitHub Desktop.
Crystal Terminal Prompt Helper Functions
def prompt_input(prompt_text, *, default = nil) : String
print prompt_text
if default
print %[ (default: "], default, %[")]
end
print " "
gets || default || ""
end
def prompt_integer_input(prompt_text)
until (user_in = (prompt_input prompt_text).to_i?)
puts "Input must be an integer!"
end
user_in
end
def prompt_enum_input(prompt_text, enum_type : Enum.class)
until (user_in = enum_type.parse?(prompt_input prompt_text))
puts "Input must be one of #{enum_type.values}!"
end
user_in
end
DATE_FORMAT = Time::Format.new "%Y%m%d", Time::Location.local
def prompt_date_input(prompt_text)
date_input = nil
until date_input
begin
user_in = prompt_input prompt_text
date_input_parsed = DATE_FORMAT.parse user_in
date_input = date_input_parsed
rescue exception : Time::Format::Error | ArgumentError
puts "Invalid date! Input valid year in YYYYMMDD format."
end
end
date_input
end
def yes_no_to_boolean?(input_string)
case input_string.downcase
when "yes", "y"
true
when "no", "n"
false
else
nil
end
end
def prompt_yes_no_input(prompt_text)
while (user_in = yes_no_to_boolean?(prompt_input prompt_text)).nil?
puts %(Input must be one of ["yes", "y", "no", "n"]!)
end
user_in
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment