2011-03-25 39 views
31

我想运行一个Rake任务,要求用户输入。是否可以制作交互式Rake任务?

我知道我可以在命令行提供输入,但我要问用户是否是肯定他们想用的情况下,特定的行动来进行,他们错误地输入提供给Rake任务中的一个值。

+6

看看[Thor](https://github.com/wycats/thor)来代替交互式任务。它远远优于Rake,并且它配备了Rails,所以你已经拥有了它而不需要安装任何东西。 – meagar 2012-07-09 03:10:09

+0

@meagar今天刚刚遇到了这个问题,我被困住了,你有没有想过这个?我在用zsh在Mac上。 。 。 – 2016-06-06 23:45:29

+0

只是想出了它 - 它显然是与Rails zsh插件相关的。当我删除该插件时,重新启动zsh,然后重新添加它,问题消失。 。 。 – 2016-06-06 23:53:13

回答

69

像这样的东西可能会奏效

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 

任务重新启用,并从How to run Rake tasks from within Rake tasks?

+0

任何想法,当这个代码会显示“^ M”,当输入“否”后按下输入键? – 2014-06-15 00:34:33

5

用户输入一个方便的功能是把它放在一个do..while循环,只有当用户提供有效继续调用输入。 Ruby没有明确地使用这种结构,但是您可以使用beginuntil来实现同样的效果。这将增加接受的答案如下:

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 
1

这是一个没有使用其他任务的例子。

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 
相关问题