我有一个 Rakefile 我通常会从命令行调用 Rake 任务:

rake blog:post Title

我想编写一个 Ruby 脚本来多次调用该 Rake 任务,但我看到的唯一解决方案是使用 `` (反引号)或 system.

这样做的正确方法是什么?

有帮助吗?

解决方案

timocracy.com:

require 'rake'
require 'rake/rdoctask'
require 'rake/testtask'
require 'tasks/rails'

def capture_stdout
  s = StringIO.new
  oldstdout = $stdout
  $stdout = s
  yield
  s.string
ensure
  $stdout = oldstdout
end

Rake.application.rake_require '../../lib/tasks/metric_fetcher'
results = capture_stdout {Rake.application['metric_fetcher'].invoke}

其他提示

这适用于 Rake 版本 10.0.3:

require 'rake'
app = Rake.application
app.init
# do this as many times as needed
app.add_import 'some/other/file.rake'
# this loads the Rakefile and other imports
app.load_rakefile

app['sometask'].invoke

正如克努特所说,使用 reenable 如果你想多次调用。

您可以使用 invokereenable 第二次执行任务。

您的示例调用 rake blog:post Title 好像有参数该参数可以作为参数使用 invoke:

例子:

require 'rake'
task 'mytask', :title do |tsk, args|
  p "called #{tsk} (#{args[:title]})"
end



Rake.application['mytask'].invoke('one')
Rake.application['mytask'].reenable
Rake.application['mytask'].invoke('two')

请更换 mytaskblog:post 而任务定义你可以 require 你的rakefile。

该解决方案会将结果写入标准输出 - 但您没有提到您想要抑制输出。


有趣的实验:

您可以致电 reenable 也在任务定义内。这允许任务重新启用自己。

例子:

require 'rake'
task 'mytask', :title do |tsk, args|
  p "called #{tsk} (#{args[:title]})"
  tsk.reenable  #<-- HERE
end

Rake.application['mytask'].invoke('one')
Rake.application['mytask'].invoke('two')

结果(使用 rake 10.4.2 测试):

"called mytask (one)"
"called mytask (two)"

在加载了 Rails 的脚本中(例如 rails runner script.rb)

def rake(*tasks)
  tasks.each do |task|
    Rake.application[task].tap(&:invoke).tap(&:reenable)
  end
end

rake('db:migrate', 'cache:clear', 'cache:warmup')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top