我想運行一個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