簡體   English   中英

如何從 rake 任務中返回一些值

[英]How to return some value from rake task

如何從 ruby​​ 中的Rake任務返回一些值。

示例代碼:

namespace tasks
    task task1: :environment do |task|
      log = "Running task"
      puts log
      log << "Done"
      return log # suggest how to do this
    end
end

我正在運行 rake 任務: Rake::Task['tasks:task1'].invoke 如何獲取變量中的返回值,如下所示:

result = Rake::Task['tasks:task1'].invoke

嘗試使用錯誤消息中止並捕獲該消息。

根據您嘗試返回的內容,您可以嘗試使用錯誤消息中止任務,該消息可以從您調用任務的位置“捕獲”。 然后您可以看到錯誤消息是什么。

你的任務

namespace :tasks
  task task1: :environment do |task|
    log = "Running task... "
    puts log
    log << "Done!"
    abort( log )
  end
end

運行你的任務

begin
  Rake::Task[ "tasks:task1" ].invoke
rescue SystemExit => exit
  puts exit.message #=> "Running task... Done!" 
end

它並不完全優雅,但取決於您要返回的內容,它可以滿足您的需求。

task :return_a_value do
  '123'
end

task :hello do
  result = Rake::Task['return_a_value'].invoke.first.call
  puts result
end

現在調用:

$ rake hello
123

假設您希望任務結果在其他任務中:


config = ''

task :load_config do
  config = 'some config' # this could be reading from a file or API
end

# this tasks depends on the other
task use_config: [:load_config] do
  puts config
end

然后:

$ bundle exec rake use_config
some config

您可以使用代碼退出 rake 任務,然后使用 $?

但也許 rake 可能不是這項工作的正確工具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM