Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't open CSV file: no implicit conversion of StringIO into String

I want to read a CSV file produced by an export from one of my controllers. Here is the simple code:

def export_houses

  houses_file = open("http://127.0.0.1:3000/houses/export.csv")

  houses = CSV.open(houses_file, 'r:bom|utf-8', { headers: true })

  ...

end

The problem occurs on the CSV.open line, where I get the following error message:

TypeError: no implicit conversion of StringIO into String
from /Users/htaidirt/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/csv.rb:1256:in `initialize'

houses_file is correctly found. It's a StringIO class, but I wanted a File class to use with CSV.open.

Do you have an idea how to proceed? Thanks.

like image 825
htaidirt Avatar asked Dec 03 '22 18:12

htaidirt


1 Answers

You can read a csv file from http server like this :

require 'open-uri'
require 'csv'
url = 'http://127.0.0.1:3000/houses/export.csv'
houses = CSV.new(open(url), :headers => :first_row)

or you can parse it with parse method

require 'open-uri'
require 'csv'
url = 'http://127.0.0.1:3000/houses/export.csv'
houses = CSV.parse(open(url).read, :headers => true)

Hope this helps

like image 63
Yann VERY Avatar answered Dec 05 '22 09:12

Yann VERY