Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create / Rename a tempfile in rails using open() method

I am trying to create a tempfile, which i am downloading from a URL: for example this JPEG image which has no extension in the URL:

http://s7d9.scene7.com/is/image/jewelrymedia/Verragio14123_V_918_CU7

You can see it does not have a .jpg extension... So i'd like to save it as a tempfile, but before saving append the .jpg extension to it. Is this possible? Or if thats not possible, rename the tempfile after saving?

Right now, i am able to create the temp file by saying file = open("http://s7d9.scene7.com/is/image/jewelrymedia/Verragio14123_V_918_CU7")

Which writes the temp file... But this does not help, as the temp file also has no extension

#<Tempfile:/var/folders/3m/t1v11gzj32n0fdbhwr823y600000gn/T/open-uri20150309-21935-qw7870>

like image 593
Joel Grannas Avatar asked Mar 17 '23 19:03

Joel Grannas


1 Answers

As you can see here you can't specify extension for Tempfile downloaded through open-uri.

So, just create new Tempfile with .jpg extension and write downloaded file to it:

require 'tempfile'
require 'open-uri'

input_file = open('http://s7d9.scene7.com/is/image/jewelrymedia/Verragio14123_V_918_CU7')

output_file = Tempfile.new(['output', '.jpg'])

output_file.binmode
output_file.write input_file.read
output_file.flush

output_file.seek(0)

p output_file.path
p output_file.size
like image 108
Maxim Avatar answered Apr 01 '23 09:04

Maxim