Created
December 19, 2018 22:21
-
-
Save tristanmorgan/340afe5883652d0399fc3e372b64cc6f to your computer and use it in GitHub Desktop.
lib/thor/line_editor/basic.rb - print stars for no-echo input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Thor | |
module LineEditor | |
class Basic | |
attr_reader :prompt, :options | |
def self.available? | |
true | |
end | |
def initialize(prompt, options) | |
@prompt = prompt | |
@options = options | |
end | |
def readline | |
$stdout.print(prompt) | |
get_input | |
end | |
private | |
def get_input | |
if echo? | |
$stdin.gets | |
else | |
require 'io/console' | |
password = '' | |
loop do | |
character = $stdin.getch | |
break unless character | |
if ["\n", "\r"].include? character | |
puts '' | |
break | |
elsif ["\b", "\u007f"].include? character | |
password.chop! | |
print "\b\e[P" | |
elsif character == "\u0003" | |
exit 1 | |
else | |
print '*' | |
password << character | |
end | |
end | |
password | |
end | |
end | |
def echo? | |
options.fetch(:echo, true) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment