如何使用 rake 命令在命名空间的每个任务上运行函数

发布于 2024-11-07 01:37:20 字数 465 浏览 1 评论 0原文

我想在命名空间中的每个 rake 任务上运行一个简单的函数 Enter_to_continue 。 目前我在每个任务的末尾添加该函数

,但是,这似乎是多余的,有没有办法通过进行一些元编程来运行这个函数,enter_to_continue,在命名空间“mytest”的每个任务的末尾自动运行?

namespace :mytest do
  task :foo do
    system "date"
    enter_to_continue
  end

  task :bar do 
    system "ls"
    enter_to_continue
  end

  # ...
  # Let's say 10 more tasks ends with enter_to_continue comes after 
  # ...
end

def enter_to_continue
  STDIN.gets.chomp
end

I want to run a simple function, enter_to_continue on every rake task in a namespace.
currently I add that function at the end of every single task

however, it seems redundant, is there any way to run this function, enter_to_continue, to run at the end of every task of namespace 'mytest' automatically, by doing some meta programming?

namespace :mytest do
  task :foo do
    system "date"
    enter_to_continue
  end

  task :bar do 
    system "ls"
    enter_to_continue
  end

  # ...
  # Let's say 10 more tasks ends with enter_to_continue comes after 
  # ...
end

def enter_to_continue
  STDIN.gets.chomp
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赴月观长安 2024-11-14 01:37:20

您可以尝试 Rake::Task#enhance:

require 'rake'

ns = namespace :mytest do

  task :foo do |t|
    puts "You called task #{t}"
  end

  task :bar do |t|
    puts "You called task #{t}"
  end

  # ...
  # Let's say 10 more tasks ends with enter_to_continue comes after 
  # ...
end

#
#Add actions to each task (e.g. enter_to_continue)
#
ns.tasks.each{|tsk|
  tsk.enhance { puts "\treached method #{__method__}" }
}

#Test the result
task :default => "mytest:foo"
task :default => "mytest:bar"
if $0 == __FILE__
  Rake.application[:default].invoke
end

编辑:
您还可以在定义块内增强任务:

namespace :mytest do |ns|
  # 
  #...Task definitions...
  #
  ns.tasks.each{|tsk|
    tsk.enhance { puts "\treached method #{__method__}" }
  }
end

You could try Rake::Task#enhance:

require 'rake'

ns = namespace :mytest do

  task :foo do |t|
    puts "You called task #{t}"
  end

  task :bar do |t|
    puts "You called task #{t}"
  end

  # ...
  # Let's say 10 more tasks ends with enter_to_continue comes after 
  # ...
end

#
#Add actions to each task (e.g. enter_to_continue)
#
ns.tasks.each{|tsk|
  tsk.enhance { puts "\treached method #{__method__}" }
}

#Test the result
task :default => "mytest:foo"
task :default => "mytest:bar"
if $0 == __FILE__
  Rake.application[:default].invoke
end

Edit:
You may enhance the tasks also inside the definition block:

namespace :mytest do |ns|
  # 
  #...Task definitions...
  #
  ns.tasks.each{|tsk|
    tsk.enhance { puts "\treached method #{__method__}" }
  }
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文