Thor task throws error when using gets or ARGF.readline
Question
This is Thor task:
desc 'readkeys', 'Read keys'
method_option :password, :type => :string, :desc => 'Password for the key store'
def readkeys
if options[:password].nil?
puts "Enter keystore password"
options[:password] = gets
end
File.open("#{Dir.home}#{File::SEPARATOR}#{ENV['USER']}.p12") do |p12|
pkcs12 = OpenSSL::PKCS12.new(p12.read, options[:password])
end
end
When I run the command, I get this error:
./mycommand:26:in `gets': No such file or directory - readkeys (Errno::ENOENT)
Any ideas? The syntax seems fine.
Solution
Two issues I see in this. The first is that you can't actually modify the options hash from Thor. It's frozen, and you'll get a `[]=': can't modify frozen Thor::CoreExt::HashWithIndifferentAccess (RuntimeError)
.
The real issue, though, is that you're working at too low a level. What you're looking for is the ask
method of Thor::Actions
. If I understand your code properly, to do what you want to do you'd do something like this:
class Test < Thor
include Thor::Actions
desc 'readkeys', 'Read keys'
method_option :password, :type => :string, :desc => 'Password for the key store'
def readkeys
if options[:password].nil?
password = ask "Enter keystore password"
else
password = options[:password]
end
File.open("#{Dir.home}#{File::SEPARATOR}#{ENV['USER']}.p12") do |p12|
pkcs12 = OpenSSL::PKCS12.new(p12.read, password)
end
end
#...
end
Or, more simply,
class Test < Thor
include Thor::Actions
desc 'readkeys', 'Read keys'
method_option :password, :type => :string, :desc => 'Password for the key store'
def readkeys
password = options[:password] || ask("Enter keystore password")
File.open("#{Dir.home}#{File::SEPARATOR}#{ENV['USER']}.p12") do |p12|
pkcs12 = OpenSSL::PKCS12.new(p12.read, password)
end
end
#...
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow