jump to navigation

OpenURI returns two different objects September 24, 2008

Posted by John Dewey in Code, Ruby.
trackback

I am unfortunate in using ImageMagick to watermark images passed into a service. However, I noticed occasional nils when trying to read images returned by OpenURI.

Magick::Image.read(open(url).path).first

Interesting… OpenURI returns a StringIO object rather than Tempfile when data on the other end exceeds 10240 bytes.

StringMax = 10240
def <<(str)
  @io << str
  @size += str.length
  if StringIO === @io && StringMax < @size
    require 'tempfile'
    io = Tempfile.new('open-uri')
    io.binmode
    Meta.init io, @io if @io.respond_to? :meta
    io << @io.string
    @io = io
  end
end

There are several approaches to this problem, but I opted for the easy one. I simply added the following to my model to force a Tempfile.

##
# OpenURI::Buffer::StringMax = 10240
OpenURI::Buffer::StringMax = 0

Since this particular application is not under active development, and Rails _only_ uses OpenURI for ’script/plugin’ and a couple generators — I didn’t loose too much sleep.

Comments»

No comments yet — be the first.