Recently I fell into the “RFM” trap (read fu**ing manual). I had some Ajax files uploaded to my controller and to make it easier, I’ve been processing them using Tempfile class. This was not a problem (I’ve been processing their content) until I’ve decided to do an Ajax file upload which was connected to paperclip. Paperclip saves the file name with extension so when using with Tempfile instance, you might get the invalid file extension.

temp = Tempfile.new(params[:file_name])
temp.binmode
temp.write(Base64.decode64(file[:file_value]))
temp.rewind
temp

The file name is obtained with method path:

temp = Tempfile.new('demo.jpg')
temp.path #=> #<Tempfile:/tmp/demo.jpg20130403-3747-13d19dx>
user.avatar = temp
user.save!

# Paperclip object instance
user.avatar(:big) #=> '/images/users/user_avatar.jpg20130403-3747-13d19dx'

This might be a problem, because some browser won’t render image with invalid extension. However fixing this issue is really easy. It all comes down to reading the manual.

You can provide an Array instance with two elements as a first parameter. The temporary file base name will begin with the array’s first element, and end with the second element:

temp = Tempfile.new(['demo', '.jpg'])
temp.path #=> #<Tempfile:/tmp/demo20130403-3747-13d19dx.jpg>
user.avatar = temp
user.save!

Conclusion

Since this was mentioned in documentation I’ve got a lesson to always read it :)