使用gets或ARGF.readline时Thor任务抛出错误

时间:2012-07-22 13:21:09

标签: ruby thor

这是托尔的任务:

  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

当我运行命令时,我收到此错误:

  

./ mycommand:26:在`gets'中:没有这样的文件或目录 - readkeys   (错误:: ENOENT)

有什么想法吗?语法似乎很好。

1 个答案:

答案 0 :(得分:2)

我在此看到两个问题。首先,您无法实际修改Thor的选项哈希。它被冻结了,你会得到`[]=': can't modify frozen Thor::CoreExt::HashWithIndifferentAccess (RuntimeError)

但真正的问题是,你的工作水平太低了。您要找的是ask的{​​{1}}方法。如果我理解你的代码,做你想做的事,你会做这样的事情:

Thor::Actions

或者更简单地说,

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