Search code examples
rubycsvrails-activestorage

Parsing remote csv file : No such file or directory @ rb_sysopen


I am trying to parse a csv file hosted remotely. I user rails 6 and active storage. The file is stored on the ImportJob model. Its url can be accessed this way :

ImportJob.last.csv_file.url

the file does exist and is downloadable : http://res.cloudinary.com/dockcyr0z/raw/upload/rghn3zi2190nmc28qwbtr24apqxe.csv

However when trying to parse it

CSV.foreach(url, headers: true, header_converters: :symbol, col_sep: ';') do |row|
 puts row
end

Im getting Errno::ENOENT: No such file or directory @ rb_sysopen - http://res.cloudinary.com/dockcyr0z/raw/upload/rghn3zi2190nmc28qwbtr24apqxe.csv

same thing if I try to open the file first : open(url)

Why am I getting this error ? How can I parse this remote csv file ?


Solution

  • Open url with URI.parse and change CSV.foreach to CSV.parse

    CSV.parse(URI.parse(url).read, headers: true, header_converters: :symbol, col_sep: ';') do |row|
      puts row
    end
    
    # output
    
    {
        :first_name => "Souper",
         :last_name => "Man",
             :email => "[email protected]",
              :role => "CEO",
              :tags => "sales,marketing",
        :avatar_url => "http://res.cloudinary.com/dockcyr0z/image/upload/x3f65o5mepbdhi4fwvww99gjqr7p"
    }
    {
        :first_name => "Gentil",
         :last_name => "Keum",
             :email => "[email protected]",
              :role => "CEO",
              :tags => "sales,marketing",
        :avatar_url => "http://res.cloudinary.com/dockcyr0z/image/upload/x3f65o5mepbdhi4fwvww99gjqr7p"
    }
    

    Update:

    Or as Stefan suggests just URI.open(url) instead of URI.parse(url).read