如何从其他 Ruby 脚本调用标准 Rakefile 中定义的 Rake 任务? [英] How to call Rake tasks that are defined in the standard Rakefile from an other Ruby script?

查看:37
本文介绍了如何从其他 Ruby 脚本调用标准 Rakefile 中定义的 Rake 任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从其他 Ruby 脚本调用在 Rakefile 中定义的任务 - 而不是在 somefile.rake 中定义的任务?

Is it possible to call a task which is defined in a Rakefile - not in somefile.rake - from an other Ruby script?

我希望创建一个新的 Rake::Application 会自动从同一目录加载 Rakefile,但似乎并非如此.这是我目前想到的:

I was hoping that creating a new Rake::Application would automatically load the Rakefile from the same directory, but it seems that this is not the case. Here is what I came up with so far:

$LOAD_PATH.unshift File.dirname(__FILE__)
require 'rake'
require 'pp'

rake = Rake::Application.new
rake[:hello].invoke

执行此代码的结果如下:

Executing this code results in the following:

/opt/ruby/1.9.2-p180/lib/ruby/1.9.1/rake.rb:1720:in `[]': Don't know how to build task 'hello' (RuntimeError)
from script.rb:7:in `<main>'

pp rake 产生以下结果:

#<Rake::Application:0x00000101118da0
 @default_loader=#<Rake::DefaultLoader:0x00000101118b20>,
 @imported=[],
 @last_description=nil,
 @loaders=
  {".rb"=>#<Rake::DefaultLoader:0x00000101118a80>,
   ".rf"=>#<Rake::DefaultLoader:0x000001011189b8>,
   ".rake"=>#<Rake::DefaultLoader:0x00000101118800>},
 @name="rake",
 @original_dir=
  "/Users/t6d/Projects/Sandbox/Ruby/rake-from-ruby-script",
 @pending_imports=[],
 @rakefile=nil,
 @rakefiles=["rakefile", "Rakefile", "rakefile.rb", "Rakefile.rb"],
 @rules=[],
 @scope=[],
 @tasks={},
 @top_level_tasks=[],
 @tty_output=false>

@rakefilenil 有点令人恼火.

It is somehow irritating that @rakefile is nil.

欧洲中部时间 5 月 20 日下午 4:40 更新

在阅读了一段时间的 rake 源代码后,我发现您需要调用 Rake::Application#init 来初始化您新创建的 rake 应用程序:

After reading the rake source code for a little while, I figured out that you need to call Rake::Application#init in order to initialize your newly created rake application:

rake = Rake::Application.new
rake.init
rake.load_rakefile

但是,我仍然无法调用我的 Rakefile 中定义的任何任务:

However, I still cannot invoke any tasks defined in my Rakefile:

rake.top_level_tasks # => ["default"]

我很乐意在这方面提供任何帮助.

I'd gladly appreciate any help on that matter.

推荐答案

您忘记将新的 rake 添加到当前的 Rake 应用程序:

You forgot to add your new rake to the current Rake Application:

$LOAD_PATH.unshift File.dirname(__FILE__)

require 'rake'
require 'pp'

rake = Rake::Application.new
Rake.application = rake
rake.init
rake.load_rakefile

rake[:hello].invoke

或者只是

$LOAD_PATH.unshift File.dirname(__FILE__)
require 'rake'
require 'pp'

Rake.application.init
Rake.application.load_rakefile

Rake.application[:hello].invoke

这篇关于如何从其他 Ruby 脚本调用标准 Rakefile 中定义的 Rake 任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆