我有一个带有Rake任务的Rakefile,通常会从命令行调用它:
我想编写一个多次调用Rake任务的Ruby脚本,但我看到的唯一解决方案是使用``(反引号)或system进行炮击。
什么是正确的方法?
来自timocracy.com:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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} |
这适用于Rake 10.0.3版:
1 2 3 4 5 6 7 8 9
| 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。
您可以使用invoke和reenable再次执行任务。
您的示例调用rake blog:post Title似乎有一个参数。 此参数可用作invoke中的参数:
例:
1 2 3 4 5 6 7 8 9 10
| 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') |
请用blog:post替换mytask,而可以使用raxfile require代替任务定义。
此解决方案会将结果写入stdout-但您没有提到要抑制输出。
有趣的实验:
您也可以在任务定义内调用reenable。 这允许任务重新启用自己。
例:
1 2 3 4 5 6 7 8
| 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测试):
1 2
| "called mytask (one)"
"called mytask (two)" |
在加载了Rails的脚本中(例如rails runner script.rb)
1 2 3 4 5 6 7
| def rake(*tasks)
tasks.each do |task|
Rake.application[task].tap(&:invoke).tap(&:reenable)
end
end
rake('db:migrate', 'cache:clear', 'cache:warmup') |