我有一个rake
任务和我需要处理的CSV文件;它们位于lib\tasks
目录的子目录中:
\foo
one.csv
two.csv
...
foo.rake
任务:
task foo: :environment do
# for each file in directory
Dir.foreach("./*.csv") do |file| # not valid
# process CSV file's content
CSV.foreach(file, {:headers => true, :col_sep => ";"}) do |row|
...
end
end # Dir
end # task
如何引用与rake任务相关的文件?
答案 0 :(得分:2)
我更多地考虑了这一点,我认为合并File.join
和Dir.glob
将允许您处理所有csv文件:
require "csv"
foo_dir = File.join(Rails.root, "lib", "tasks", "foo")
task foo: :environment do
# for each file in directory
Dir.glob(foo_dir + "/*.csv") do |csv_file|
# process CSV file's content
CSV.foreach(csv_file, {:headers => true, :col_sep => ";"}) do |row|
#...
end
end # Dir
end # task
编辑:正如@craig在下面的评论中指出的那样,使用File.dirname
和__FILE__
可以更简洁地完成此任务:
require "csv"
task foo: :environment do
# for each file in directory
Dir.glob(File.dirname(__FILE__) + "/*.csv").each do |file|
# process CSV file's content
CSV.foreach(csv_file, {:headers => true, :col_sep => ";"}) do |row|
#...
end
end # Dir
end # task