ruby Thor中limited_options的别名

5n0oy7gb  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(117)

我想在Thor中请求用户输入,但有别名:

$ Is this correct?: [yes, no, maybe] (yes)

字符串
目前我有这个:

class CLI < Thor
  desc 'do_thing', 'does a thing'
  def do_thing      
    answer = ask("Is this correct?", limited_to: %w{yes no maybe}, default: 'yes')
    # do stuff
  end
end


我想让用户只输入每个选项的第一个字母。
但我得到的回应是:

$ Your response must be one of: [yes, no, maybe]. Please try again.

rsl1atfo

rsl1atfo1#

您不能为ask添加别名,因为答案将直接与limited_to中提供的选项列表匹配。Source
如果你真的想要这个功能,你最好的选择是跳过limited_options,而是在事实发生后检查答案并相应地做出回应,例如。

class MyCLI  < Thor
  desc 'do_thing', 'does a thing'
  def do_thing      
    answer = ask("Is this correct? (Y)es/(N)o/(M)aybe:", default: 'Y')
    unless %w(y n m yes no maybe).include?(answer.downcase)
      puts "[#{answer}] is an invalid option. Please try again."
      send(__method__)
    end 
    puts answer
  end
end

字符串
示例如下:

Is this correct? (Y)es/(N)o/(M)aybe: (Y) Test 
[Test] is an invalid option. Please try again.
Is this correct? (Y)es/(N)o/(M)aybe: (Y) Yes 
Yes


如果你想使用内置的有限的选项,那么你可以使用这样的东西,但在我看来,这是没有吸引力时,在CLI中表示:

class CLI < Thor
  desc 'do_thing', 'does a thing'
  def do_thing      
    answer = ask("Is this correct? (Y)es/(N)o/(M)aybe", limited_to: %w{y n m}, default: 'y', case_insensitive: true)
  end
end


它将输出为:

Is this correct? (Y)es/(N)o/(M)aybe [y,n,m] (y)

相关问题