如何在Ruby脚本中运行Rake任务?

Man*_*lla 51 ruby rake command-line-interface

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

rake blog:post Title
Run Code Online (Sandbox Code Playgroud)

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

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

tit*_*ous 43

来自timocracy.com:

require 'rake'

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

Rake.application.rake_require 'metric_fetcher', ['../../lib/tasks']
results = capture_stdout {Rake.application['metric_fetcher'].invoke}
Run Code Online (Sandbox Code Playgroud)


Kel*_*vin 17

这与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
Run Code Online (Sandbox Code Playgroud)

正如knut所说,reenable如果你想多次调用,请使用.


knu*_*nut 13

您可以再次使用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')
Run Code Online (Sandbox Code Playgroud)

请用你的rakefile 替换mytask,blog:post而不是任务定义require.

此解决方案将结果写入stdout - 但您没有提及,您想要抑制输出.


有趣的实验:

您也可以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')
Run Code Online (Sandbox Code Playgroud)

结果(用rake 10.4.2测试):

"called mytask (one)"
"called mytask (two)"
Run Code Online (Sandbox Code Playgroud)