Go back to the main page

Problems getting the attachment size in Rails 3

This article is over 2 years old. Proceed with caution.

Regards ♨ – Minimul

 

Problems with incoming emails with attachments

I just completed the Rails 3 upgrade on Simplton. I have been putting out a few fires since the move. Here is an exception I got yesterday.

Exception.

undefined method size for #<Mail::Part:0x9b82924>
/var/www/simplton/vendor/bundled/ruby/1.8/gems/mail-2.2.12/lib/mail/message.rb:1285:in method_missing

Now the exact area of the problem was this code (see arrow).

      param[:userfile].each do |upload|
        attach = Attachment.new
        attach.real = upload.original_filename
        attach.name = sanitize_filename(upload.original_filename)
    ->  attach.size = defined?(upload.length) ? upload.length : upload.size 


I must also clarify that this error only occurs when processing a file attachment from a incoming email. A file attachment from a web form works just fine. Don't mind the operator in the filesize code, this has to do with a mod_porter issue. I speculate the reason .length and/or .size methods are missing from the Rails 3 is because the Mail has replaced Tmail and this convenience method for filesize has not be added.

Solution.

# The first condition is for a email attachment (upload.decoded.length).
# Second condition is if web form attachment (upload.size). 
attach.size = defined?(upload.decoded) ? upload.decoded.length : upload.size

Going this route you are no longer dependant on different file attachment handlers and their different convenience methods.

Comment on this article?