I was writing something to copy some files to S3 for local work. Normally, you’d want to use Tempfiles for this so the file gets erased when the request is finished without you having to do your own garbage collecting.

Encodings proved to be a major hitch. Here’s the fix:

file_name = File.basename(file.key)
temp_file = Tempfile.new(file_name.split(/(.\w+)$/))
begin
	temp_file.binmode
	temp_file.write file.read

Props to Yuri for having this post up

Extra cool? Tempfile#binmode is not in the docs for Ruby 2.0 / Tempfile. And if you happen to be using Paperclip, make sure you’re using ::Tempfile and not Paperclip::Tempfile, since Paperclip overrides this non-documented function for their own purposes

Rabbit hole was deep on this one.