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

问题描述 投票:54回答:4

我有一个 Rakefile 的Rake任务,我通常会在命令行中调用。

rake blog:post Title

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

正确的方法是什么?

ruby rake command-line-interface
4个回答
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}

18
投票

这适用于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

如knut所说,使用 reenable 如果你想多次调用。


15
投票

你可以使用 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。

这个解决方案将把结果写到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')

结果 (用 rake 10.4.2 测试)。

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

3
投票

在一个加载了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')
© www.soinside.com 2019 - 2024. All rights reserved.