使用Capistrano在远程服务器上运行ruby代码时,如何请求用户输入?

时间:2019-01-31 18:37:14

标签: io capistrano capistrano3

我想在远程服务器上运行的Capistrano的任务时,以确认该操作:

task :do_someting do
  on roles(:primary) do
    within release_path do
      with rails_env: fetch(:rails_env) do
        execute :rails, :runner,
          %Q['require "do_something"; Do::Something.()']
      end
    end
  end
end

DoSomethig如下所示:

require "highline/import"

class DoSomething

  def self.call
    query_db_for_objects.each do |obj|
      answer = ask "Are you sure to do something with #{obj}? (y/n)"
      rerun unless answer == 'y'
      do_something
    end
  end

end

从远程服务器询问时,highline gem中的方法ask似乎不起作用,并且命令bundle exec cap production do_something永远挂起。

我怎样才能运行此Capistrano的任务时要求从远程服务器的用户输入?

1 个答案:

答案 0 :(得分:1)

我能够使用以下红宝石代码从远程服务器上读取用户答案

task :do_someting do

  class ConfirmHandler
    def on_data(command, stream_name, data, channel)
      if data.to_s =~ /\?$/
        prompt = Net::SSH::Prompt.default.start(type: 'confirm')
        response = prompt.ask "Please enter your response (y/n)"
        channel.send_data "#{response}\n"
      end
    end
  end

  on roles(:primary) do
    within release_path do
      with rails_env: fetch(:rails_env) do
        execute :rails, :runner,
          %Q['require "do_something"; Do::Something.()']
      end
    end
  end

end

其中Do::Something具有ask_user方法,该方法看起来如下:

class Do::Something

  def self.call
    answer = ask_user
    puts "Answer is: #{answer}"
  end

  def self.ask_user
    puts 'Do something?'
    `read response; echo $response`
  end

end