Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby open returning a string instead of a file?

When trying to open() remote images, some return as StringIO and others return as File...how do I force the File?

data = open("http://graph.facebook.com/61700024/picture?type=square")
=> #<StringIO:0x007fd09b013948>

data = open("http://28.media.tumblr.com/avatar_7ef57cb42cb0_64.png")
=> #<StringIO:0x007fd098bf9490>

data = open("http://25.media.tumblr.com/avatar_279ec8ee3427_64.png")
=> #<File:/var/folders/_z/bb18gdw52ns0x5r8z9f2ncj40000gn/T/open-uri20120229-9190-mn52fu>

I'm using Paperclip to save remote images (which are stored in S3), so basically wanting to do:

user = User.new
user.avatar = open(url)
user.save
like image 856
Shpigford Avatar asked Dec 10 '22 02:12

Shpigford


1 Answers

Open-URI has a 10KB limit on StringIO objects, anything above that and it stores it as a temp file.

One way to get past this is by actually changing the constant that Open-URI takes for the limit of StringIO objects. You can do this by setting the constant to 0;

OpenURI::Buffer.send :remove_const, 'StringMax' if OpenURI::Buffer.const_defined?('StringMax')
OpenURI::Buffer.const_set 'StringMax', 0

Add that to your initialiser and you should be good to go.

like image 98
siame Avatar answered Dec 24 '22 21:12

siame