Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FasterCSV: Read Remote CSV Files

I can't seem to get this to work. I want to pull a CSV file from a different webserver to read in my application. This is how I'd like to call it:

url = 'http://www.testing.com/test.csv'
records = FasterCSV.read(url, :headers => true, :header_converters => :symbol)

But that doesn't work. I tried Googling, and all I came up with was this excerpt: Practical Ruby Gems

So, I tried modifying it as follows:

require 'open-uri'
url = 'http://www.testing.com/test.csv'
csv_url = open(url)
records = FasterCSV.read(csv_url, :headers => true, :header_converters => :symbol)

... and I get a can't convert Tempfile into String error (coming from the FasterCSV gem).

Can anyone tell me how to make this work?

like image 934
neezer Avatar asked Nov 26 '25 10:11

neezer


2 Answers

require 'open-uri'
url = 'http://www.testing.com/test.csv'
open(url) do |f|
  f.each_line do |line|
    FasterCSV.parse(line) do |row|
      # Your code here
    end
  end
end

http://www.ruby-doc.org/core/classes/OpenURI.html http://fastercsv.rubyforge.org/

like image 73
Ryan Bigg Avatar answered Nov 28 '25 03:11

Ryan Bigg


I would retrieve the file with Net::HTTP for example and feed that to FasterCSV

Extracted from ri Net::HTTP

 require 'net/http'
 require 'uri'

 url = URI.parse('http://www.example.com/index.html')
 res = Net::HTTP.start(url.host, url.port) {|http|
   http.get('/index.html')
 }
 puts res.body
like image 37
Keltia Avatar answered Nov 28 '25 02:11

Keltia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!