我想运行一个Rake任务,要求用户输入。是否可以制作交互式Rake任务?
我知道我可以在命令行提供输入,但我要问用户是否是肯定他们想用的情况下,特定的行动来进行,他们错误地输入提供给Rake任务中的一个值。
我想运行一个Rake任务,要求用户输入。是否可以制作交互式Rake任务?
我知道我可以在命令行提供输入,但我要问用户是否是肯定他们想用的情况下,特定的行动来进行,他们错误地输入提供给Rake任务中的一个值。
像这样的东西可能会奏效
task :action do
STDOUT.puts "I'm acting!"
end
task :check do
STDOUT.puts "Are you sure? (y/n)"
input = STDIN.gets.strip
if input == 'y'
Rake::Task["action"].reenable
Rake::Task["action"].invoke
else
STDOUT.puts "So sorry for the confusion"
end
end
任何想法,当这个代码会显示“^ M”,当输入“否”后按下输入键? – 2014-06-15 00:34:33
用户输入一个方便的功能是把它放在一个do..while
循环,只有当用户提供有效继续调用输入。 Ruby没有明确地使用这种结构,但是您可以使用begin
和until
来实现同样的效果。这将增加接受的答案如下:
task :action do
STDOUT.puts "I'm acting!"
end
task :check do
# Loop until the user supplies a valid option
begin
STDOUT.puts "Are you sure? (y/n)"
input = STDIN.gets.strip.downcase
end until %w(y n).include?(input)
if input == 'y'
Rake::Task["action"].reenable
Rake::Task["action"].invoke
else
# We know at this point that they've explicitly said no,
# rather than fumble the keyboard
STDOUT.puts "So sorry for the confusion"
end
end
这是一个没有使用其他任务的例子。
task :solve_earth_problems => :environment do
STDOUT.puts "This is risky. Are you sure? (y/n)"
begin
input = STDIN.gets.strip.downcase
end until %w(y n).include?(input)
if input != 'y'
STDOUT.puts "So sorry for the confusion"
return
end
# user accepted, carry on
Humanity.wipe_out!
end
看看[Thor](https://github.com/wycats/thor)来代替交互式任务。它远远优于Rake,并且它配备了Rails,所以你已经拥有了它而不需要安装任何东西。 – meagar 2012-07-09 03:10:09
@meagar今天刚刚遇到了这个问题,我被困住了,你有没有想过这个?我在用zsh在Mac上。 。 。 – 2016-06-06 23:45:29
只是想出了它 - 它显然是与Rails zsh插件相关的。当我删除该插件时,重新启动zsh,然后重新添加它,问题消失。 。 。 – 2016-06-06 23:53:13