Ruby 1.9.2 encoding issue

[Rails 3 - Ruby 1.9.2]
I have to get email attachments ( mp4 files ) and store them…
I get easily all parts using Mail ( … <Content-Type: multipart/
mixed…"> )
attachment = mail.attachments[0]
#<Mail::Part:2206885940, Multipart: false, Headers: <Content-
Type: video/mp4; name=landscape.mp4>, <Content-Transfer-Encoding:
base64>, <Content-Disposition: attachment; filename=landscape.mp4>>
got what I need,
but trying to store this attachment in a temp file , I get an encoding
error :
File.open(filepath,File::CREAT|File::TRUNC|File::WRONLY,0644) { |
f| f.write(attachment.body) }
Encoding::UndefinedConversionError Exception: “\x80” from
ASCII-8BIT to UTF-8
did I miss anything before writing the file ? or is it a known Ruby
bug ?
being an .mp4 attachment, it should be a binary file… it comes as an
UTF-8 ( Base64) ? , right…
how should I write it as a binary too ?
tfyh

Please check +File#external_encoding+.

When +File#external_encoding+ is not +nil+, +File#write+ method tries to
change
the encoding of the written string into +File#external_encoding+.
If the written data is binary string which contains 0x80 … 0xFF and
+File#external_encoding+
is “UTF-8”, +File#write+ method tries to encode the data, but it can’t!!
So an exception will be raised. Please see following example.

binary_data = [ 0x80, 0x81 ].pack( “C*” )
File.open( “binary_data”, File::CREAT | File::TRUNC | File::WRONLY,
0644 ) do |f|
p f.external_encoding
# #Encoding:UTF-8
f.write(binary_data)
# test.rb:7:in write': "\x80" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError) # from test.rb:7:in block in ’
# from test.rb:7:in open' # from test.rb:7:in
end

How to avoid this issue?
You must open the file with BINARY MODE. The file object being binary
mode, the +File#write+
method doesn’t encode the data automatically.
See below:

binary_data = [ 0x80, 0x81 ].pack( “C*” )
File.open( “binary_data”, “w+b”, 0644 ) do |f|
p f.external_encoding
# #Encoding:ASCII-8BIT
f.write(binary_data)
# OK. NO ERROR!
end

cf. http://ruby-doc.org/ruby-1.9/classes/IO.html

Thanks a lot !

so obvious , that I could not figure anything less complicated …