Thor のlimited_options のエイリアス
概要
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.
解決策
回答は、limited_to で提供されるオプションのリストと直接照合されるため、質問するエイリアスを追加することはできません。ソース
本当にこの機能が必要な場合、最善の策は、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)