从 rake 任务中删除重复项
Remove duplication from rake tasks
我有三个修改实例变量然后调用任务的 rake 任务 :find
,这是 Rakefile:
@tags = ['OPTIMIZE', 'TODO', 'FIXME']
task :optimize do
@tags = ['OPTIMIZE']
Rake::Task["find"].invoke
end
task :todo do
@tags = ['TODO']
Rake::Task["find"].invoke
end
task :fixme do
@tags = ['FIXME']
Rake::Task["find"].invoke
end
task :find do
# finds words depending on @tags
end
我想从 Rakefile 中删除重复项并使其更简洁。我如何简化(或合并)这个 Rakefile 中的 :optimize、:todo、:fixme 任务?
Rake 任务可以接受参数,因此您可以传递标签而不是依赖实例变量:
TAGS = ['OPTIMIZE', 'TODO', 'FIXME']
task :find, [:tags] do |task, args|
# command lines can't pass an array, afaik; so if we pass the
# tags in, we'll need them as a space separated list
tags = if args[:tags]
args[:tags].split(' ')
else
TAGS
end
puts "finding all tags marked: #{tags.inspect}"
end
然后在命令行上:
% rake find[TODO OPTIMIZE] # may need escaped: rake find\[TODO\ OPTIMIZE\]
finding all tags marked: ["TODO", "OPTIMIZE"]
% rake find
finding all tags marked: ["OPTIMIZE", "TODO", "FIXME"]
然后,如果您仍然希望命名任务作为别名,传递某些参数,您可以通过 invoke
:
传递它们
TAGS.each do |tag|
task tag.downcase.to_sym do
Rake::Task["find"].invoke(tag)
end
end
并打电话给他们:
% rake todo
finding all tags marked: ["TODO"]
% rake fixme
finding all tags marked: ["FIXME"]
% rake optimize
finding all tags marked: ["OPTIMIZE"]
我有三个修改实例变量然后调用任务的 rake 任务 :find
,这是 Rakefile:
@tags = ['OPTIMIZE', 'TODO', 'FIXME']
task :optimize do
@tags = ['OPTIMIZE']
Rake::Task["find"].invoke
end
task :todo do
@tags = ['TODO']
Rake::Task["find"].invoke
end
task :fixme do
@tags = ['FIXME']
Rake::Task["find"].invoke
end
task :find do
# finds words depending on @tags
end
我想从 Rakefile 中删除重复项并使其更简洁。我如何简化(或合并)这个 Rakefile 中的 :optimize、:todo、:fixme 任务?
Rake 任务可以接受参数,因此您可以传递标签而不是依赖实例变量:
TAGS = ['OPTIMIZE', 'TODO', 'FIXME']
task :find, [:tags] do |task, args|
# command lines can't pass an array, afaik; so if we pass the
# tags in, we'll need them as a space separated list
tags = if args[:tags]
args[:tags].split(' ')
else
TAGS
end
puts "finding all tags marked: #{tags.inspect}"
end
然后在命令行上:
% rake find[TODO OPTIMIZE] # may need escaped: rake find\[TODO\ OPTIMIZE\]
finding all tags marked: ["TODO", "OPTIMIZE"]
% rake find
finding all tags marked: ["OPTIMIZE", "TODO", "FIXME"]
然后,如果您仍然希望命名任务作为别名,传递某些参数,您可以通过 invoke
:
TAGS.each do |tag|
task tag.downcase.to_sym do
Rake::Task["find"].invoke(tag)
end
end
并打电话给他们:
% rake todo
finding all tags marked: ["TODO"]
% rake fixme
finding all tags marked: ["FIXME"]
% rake optimize
finding all tags marked: ["OPTIMIZE"]