How to use input filename to generate output filename with Rake?

人走茶凉 提交于 2019-12-12 09:08:31

问题


I've got some input files which I want to encode using Ruby. The output from the encoding should match some pattern based on the filename of the input file. In order to not do this by hand, I want to use Rake as help for automation. Further I'd like to not specify a single task for every input file.

I've tried some FileList "magic" but it didn't work out. Here's the code:

desc 'Create all output from specified input'
task :encode do
  FileList['input/*.txt'].each {|input| file "output/output_#{input}" => input}
end

Anyone can help? I didn't find find anything on the web about multiple output files as dependency.


回答1:


I would look into using Rake's rule tasks, which allow tasks to be dynamically defined based on regex rules. See the rakefile rdoc page for details, but here's an example:

# creates the 'output' directory on demand
directory "output"

# define a task rule covering all the output files
rule %r{output/output_} => ['output', proc {|task_name| "input/#{task_name.sub('output/output_', '')}.txt"}] do |t|
  # replace this with your encoding logic
  sh "echo 'file #{t.source}' > #{t.name}"
end

# define a top-level 'encode' task which depends on all the 'output/output_*' tasks
task :encode => Dir['input/*.txt'].map {|x| "output/output_#{File.basename(x).sub('.txt', '')}"}

And then you should be able to run rake encode in a directory with files matching input/*, and have the output files be placed in output/output_*.



来源:https://stackoverflow.com/questions/15493501/how-to-use-input-filename-to-generate-output-filename-with-rake

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!