Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't convert StringIO into String (TypeError) in Ruby

Tags:

ruby

zip

open-uri

When I use the code below, I get the following error message: can't convert StringIO into String (TypeError)

array_of_lines = []
Zip::ZipInputStream::open(open("URL for zipped file", "rb")) do |io|
  file = io.get_next_entry
  puts "Downloading file #{file}"
  array_of_lines = io.readlines
  print "Downloaded ", array_of_lines.count, " elements.", "\n"
end

Can someone help me? Thank in advance.

like image 791
Vadim Baldin Avatar asked Nov 09 '12 10:11

Vadim Baldin


2 Answers

The information you're reading is small enough that it can be contained in a stringIO object. What normally happens is that as the data gets too large (over the default of 10KB) the object is taken out of the buffer and turned into a temp file, which you need to be to read it the way that you're trying to.

You have two options:
1. read from larger files
2. set the default for the openURI string buffer to 0.

To set the default buffer, you need to create an initializer and put this in it:

OpenURI::Buffer.send :remove_const, 'StringMax'
OpenURI::Buffer.const_set 'StringMax', 0

The first line will delete the current buffer setting (10KB) and the second line will set it to 0.

Don't forget to restart your server since it's an initializer or nothing will change. I hope that helps!

like image 77
jeffreymatthias Avatar answered Sep 28 '22 22:09

jeffreymatthias


The expression open("URL for zipped file", "rb") returns StringIO, not String.

For getting content of StringIO it's necessary to call method read

string = open(url).read()
like image 21
Denis Kreshikhin Avatar answered Sep 29 '22 00:09

Denis Kreshikhin