【发布时间】:2011-12-09 17:37:48
【问题描述】:
是否可以在 Rake 中为命名空间起别名?
我喜欢你如何给任务起别名:
task :commit => :c
希望能够做这样的事情:
namespace :git => :g
【问题讨论】:
-
你绝对应该接受克努特的回答。
标签: namespaces rake alias
是否可以在 Rake 中为命名空间起别名?
我喜欢你如何给任务起别名:
task :commit => :c
希望能够做这样的事情:
namespace :git => :g
【问题讨论】:
标签: namespaces rake alias
与
task :commit => :c
您没有定义别名,而是设置了先决条件。
当您调用:commit 时,先调用:c。
只要只有一个先决条件且:commit 不包含自己的代码,它可能看起来像一个别名,但事实并非如此。
知道了这一点,如果您 define a default task for your namespace 并为此任务设置了先决条件(并且先决条件可能再次是另一个命名空间的默认任务),您可以“别名”您的命名空间。 p>
但我认为,没有必要给命名空间起别名。如果您为命名空间定义一个默认任务并且可能为该任务定义“别名”就足够了。
再次阅读问题后,我有了另一个想法,基于Is there a “method_missing” for rake tasks?:
require 'rake'
namespace :long_namespace do
task :a do |tsk|
puts "inside #{tsk.name}"
end
end
rule "" do |tsk|
aliastask = tsk.name.sub(/short:/, 'long_namespace:')
Rake.application[aliastask].invoke
end
Rake.application['short:a'].invoke
该规则定义了一个task_missing-规则并尝试替换命名空间(在示例中它用“long_namespace”替换“short”)。
缺点:未定义的任务不会返回错误。所以你需要一个改编版:
require 'rake'
namespace :long_namespace do
task :a do |tsk|
puts "inside #{tsk.name}"
end
end
rule "" do |tsk|
aliastask = tsk.name.sub(/short:/, 'long_namespace:')
if Rake.application.tasks.map{|tsk| tsk.name }.include?( aliastask )
Rake.application[aliastask].invoke
else
raise RuntimeError, "Don't know how to build task '#{tsk.name}'"
end
end
Rake.application['short:a'].invoke
Rake.application['short:undefined'].invoke
还有一个更通用的版本,使用新方法 aliasnamespace 来定义别名命名空间:
require 'rake'
#Extend rake by aliases for namespaces
module Rake
ALIASNAMESPACES = {}
end
def aliasnamespace(alias_ns, original_ns)
Rake::ALIASNAMESPACES[alias_ns] = original_ns
end
rule "" do |tsk|
undefined = true
Rake::ALIASNAMESPACES.each{|aliasname, origin|
aliastask = tsk.name.sub(/#{aliasname}:/, "#{origin}:")
if Rake.application.tasks.map{|tsk| tsk.name }.include?( aliastask )
Rake.application[aliastask].invoke
undefined = false
end
}
raise RuntimeError, "Don't know how to build task '#{tsk.name}'" if undefined
end
#And now the usage:
namespace :long_namespace do
task :a do |tsk|
puts "inside #{tsk.name}"
end
end
aliasnamespace :short, 'long_namespace'
Rake.application['short:a'].invoke
#~ Rake.application['short:undefined'].invoke
【讨论】:
rake generate:migration 和rake g:migration 会很棒。