3

I wrote this rake task that enables me to read a csv file from a file on the local filesystem of my app, but how do I tweak this to make it read a file from a url?

desc "This class will read a csv file and display its contents on the screen"

 task :read_csv => :environment do |t, args|
 require "csv"

 csv_text = File.read('someFile.csv')
 csv = CSV.parse(csv_text, :headers=>true)
 csv.each do |row|
   puts row
 end
end

Would appreciate if someone can help me with either the code or some current links. Most of the links Im finding are for previous versions of rails where FasterCSV was not part of ruby.

Thanks

banditKing
  • 9,405
  • 28
  • 100
  • 157

2 Answers2

7

Open-uri help to read remote files

require 'csv'
require 'open-uri'

csv_text = open('http://www.vvv.hh.yyy.ggg/~hhhh/uuuu.csv')
csv = CSV.parse(csv_text, :headers=>true)
csv.each do |row|
  puts row
end
banditKing
  • 9,405
  • 28
  • 100
  • 157
Pritesh Jain
  • 9,106
  • 4
  • 37
  • 51
5

What about using NET::HTTP?

desc "This class will read a csv file from url and display its contents on the screen"

  task :read_csv => :environment do |t, args|
  require "csv"
  require 'net/http'

  uri = URI('http://www.xxx.ccc.xxx.ca/~xxx/xxx.csv')
  csv_text = Net::HTTP.get(uri)
  csv = CSV.parse(csv_text, :headers=>true)
  csv.each do |row|
    puts row
  end
end

That is just a little tweak for only getting it from an url and without https, but you got the idea, right? :)

banditKing
  • 9,405
  • 28
  • 100
  • 157
markusschwed
  • 142
  • 4