Why Does Ruby Open-Uri's Open Return a Stringio in My Unit Test, But a Fileio in My Controller

Why does Ruby open-uri's open return a StringIO in my unit test, but a FileIO in my controller?

The code responsible for this is in the Buffer class in open-uri. It starts by creating a StringIO object and only creates an actual temp file in the local filesystem when the data exceeds a certain size (10 KB).

I assume that whatever data your test is loading is small enough to be held in a StringIO and the images you are using in the actual application are large enough to warrant a TempFile. The solution is to use methods which are common to both classes, in particular the read method, with MiniMagick::Image#from_blob:

temp_image = MiniMagick::Image.from_blob(open(self.public_filename, &:read))

Why does OpenURI treat files under 10kb in size as StringIO?

When one does network programming, you allocate a buffer of a reasonably large size and send and read units of data which will fit in the buffer. However, when dealing with files (or sometimes things called BLOBs) you cannot assume that the data will fit into your buffer. So, you need special handling for these large streams of data.

(Sometimes the units of data which fit into the buffer are called packets. However, packets are really a layer 4 thing, like frames are at layer 2. Since this is happening a layer 7, they might better be called messages.)

For replies larger than 10K, the open-uri library is setting up the extra overhead to write to a stream objects. When under the StringMax size, it just includes the string in the message, since it knows it can fit in the buffer.

Save and parse CSV file from URL

This should read from remote, write and then parse the file:

require 'open-uri'
require 'csv'
url = "https://mydomain/manage/reporting/index?who=user&users=0&teams=0&datasetName=0&startDate=2015-10-18&endDate=2015-11-17&format=csv"

download = open(url)
IO.copy_stream(download, 'test.csv')
CSV.new(download).each do |l|
puts l
end

Storing image using open URI and paperclip having size less than 10kb

Try:

def icon_from_url(url)
extname = File.extname(url)
basename = File.basename(url, extname)

file = Tempfile.new([basename, extname])
file.binmode

open(URI.parse(url)) do |data|
file.write data.read
end

file.rewind

self.icon = file
end

Save and parse CSV file from URL

This should read from remote, write and then parse the file:

require 'open-uri'
require 'csv'
url = "https://mydomain/manage/reporting/index?who=user&users=0&teams=0&datasetName=0&startDate=2015-10-18&endDate=2015-11-17&format=csv"

download = open(url)
IO.copy_stream(download, 'test.csv')
CSV.new(download).each do |l|
puts l
end


Related Topics



Leave a reply



Submit