Reputation: 26262
I have a rake
task and CSV files that I need to process; they are located in sub-directory of the lib\tasks
directory:
\foo
one.csv
two.csv
...
foo.rake
The task:
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
How do I references files that are relative to the rake task?
Upvotes: 1
Views: 2050
Reputation: 2713
I got to thinking about this more and I think combining File.join
and Dir.glob
will allow you to process all your csv files:
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
EDIT: As @craig pointed out in the comment below, this can be accomplished more succinctly by using File.dirname
and __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
Upvotes: 3