简体   繁体   中英

Process CSV files in location relative to rake task

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM