how to run a function on every task of a namespace with rake command
I want to run a simple function, enter_to_continue on every rake task in a namespace开发者_JAVA技巧. 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
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
精彩评论