如何在Rake中获取当前命名空间?

时间:2022-05-19 07:22:58
namespace :baseline do
  INDEX_DIR = index(:baseline) # context
  task(:foo) ...
end

How do I get the :baseline Symbol in this context?

如何在此上下文中获取:baseline符号?

3 个解决方案

#1


8  

namespace :baseline do |namespace|
  scope = namespace.instance_variable_get("@scope")

  INDEX_DIR = index(scope)

  task(:foo) ...
end

#2


4  

There is a much cleaner way now:

现在有一种更清洁的方式:

namespace :baseline do
  scope = Rake.application.current_scope
  puts scope.path
end 

I needed this to define dynamic tasks, so not having to pass the namespace to the block is a big plus.

我需要这个来定义动态任务,所以不必将命名空间传递给块是一个很大的优点。

#3


1  

In addition to Dmitris answer with Rake.application.current_scope:

除了Dmitris用Rake.application.current_scope回答:

namespace :baseline do |namespace|
  scope = namespace.scope.path
  #...
end

scope will be "baseline" (String, not the requested Symbol).

范围将是“基线”(字符串,而不是请求的符号)。

But in rake you can define the namespace with symbol or string, you can also define like this:

但是在rake中你可以用符号或字符串定义命名空间,你也可以这样定义:

namespace 'baseline' do |namespace|
  scope = namespace.scope.path
  #...
end 

The scope will be the same with both definitions.

两个定义的范围都相同。

If you really need the Symbol, you can use scope.to_sym.

如果您确实需要Symbol,可以使用scope.to_sym。

#1


8  

namespace :baseline do |namespace|
  scope = namespace.instance_variable_get("@scope")

  INDEX_DIR = index(scope)

  task(:foo) ...
end

#2


4  

There is a much cleaner way now:

现在有一种更清洁的方式:

namespace :baseline do
  scope = Rake.application.current_scope
  puts scope.path
end 

I needed this to define dynamic tasks, so not having to pass the namespace to the block is a big plus.

我需要这个来定义动态任务,所以不必将命名空间传递给块是一个很大的优点。

#3


1  

In addition to Dmitris answer with Rake.application.current_scope:

除了Dmitris用Rake.application.current_scope回答:

namespace :baseline do |namespace|
  scope = namespace.scope.path
  #...
end

scope will be "baseline" (String, not the requested Symbol).

范围将是“基线”(字符串,而不是请求的符号)。

But in rake you can define the namespace with symbol or string, you can also define like this:

但是在rake中你可以用符号或字符串定义命名空间,你也可以这样定义:

namespace 'baseline' do |namespace|
  scope = namespace.scope.path
  #...
end 

The scope will be the same with both definitions.

两个定义的范围都相同。

If you really need the Symbol, you can use scope.to_sym.

如果您确实需要Symbol,可以使用scope.to_sym。