Just Another Tech Journal



OpenURI's open, Tempfile and StringIO

02 OCTOBER 2013

OpenURI#open has a dual personality. Consider the code below..

require 'open-uri'

zipfile = open("")

With this, zipfile can either be a Tempfile instance or a StringIO instance.

Apparently, that's how OpenURI#open works, and this StackOverFlow post explains it well. And as mentioned in the same post, to get OpenURI#open to always return a Tempfile, apply the initializer "hack".

require 'open-uri'

# Don't allow downloaded files to be created as StringIO. Force a tempfile to be created.
OpenURI::Buffer.send :remove_const, 'StringMax' if OpenURI::Buffer.const_defined?('StringMax')
OpenURI::Buffer.const_set 'StringMax', 0

Or, you can just be deterministic and create the Tempfile yourself.

comments powered by Disqus