【问题标题】:Rake Namespace Alias耙命名空间别名
【发布时间】:2011-12-09 17:37:48
【问题描述】:

是否可以在 Rake 中为命名空间起别名?


我喜欢你如何给任务起别名:

task :commit => :c

希望能够做这样的事情:

namespace :git => :g

【问题讨论】:

  • 你绝对应该接受克努特的回答。

标签: namespaces rake alias


【解决方案1】:

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

【讨论】:

  • “需要”命名空间别名的简单示例。我在没有 Rails 的情况下使用 AR,我想将一些 Rails 命令重新创建为 Rake 任务。拥有rake generate:migrationrake g:migration 会很棒。
  • @Jerska 你让我重新思考这个问题:我添加了第二个答案。
  • 哇,真的很棒的答案!谢谢 !愿你的名字得到尊重,你的王国早日到来,等等!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 2020-03-02
  • 1970-01-01
  • 2020-08-21
  • 2013-07-18
  • 1970-01-01
相关资源
最近更新 更多