AnApprentice
AnApprentice

Reputation: 111090

Rails 3 - Tempfile Path?

I have the following:

attachments.each do |a|
   Rails.logger.info a.filename
   tempfile = Tempfile.new("#{a.filename}", "#{Rails.root.to_s}/tmp/")
   Rails.logger.info tempfile.path
end

Where attachments is from paperclip.

Here's the output:

billgates.jpg
/Users/bhellman/Sites/cline/tmp/billgates.jpg20101204-17402-of0u9o-0

Why is the file name getting 20101204-17402-of0u9o-0 appended to at the end? That's breaking everything with paperclip etc. Anyone seen this before? For the life of I have no idea what's doing it?

Thanks

UPDATE Paperclip: Paperclip on github

a is the attachment file

tempfile = Tempfile.new("#{a.filename}", "#{Rails.root.to_s}/tmp/")
tempfile << a.body
tempfile.puts
attachments.build(
    :attachment => File.open(tempfile.path)
)

Upvotes: 22

Views: 26542

Answers (5)

andistuder
andistuder

Reputation: 506

best make sure your tempfile has the correct extension, saving you to trying and change it after:

file = Tempfile.new(['hello', '.jpg'])

file.path # => something like: "/tmp/hello2843-8392-92849382--0.jpg"

more here: http://apidock.com/ruby/v1_9_3_125/Tempfile/new/class

Upvotes: 29

Chris Nolet
Chris Nolet

Reputation: 9083

The best way I found to deal with this was to specify the file extension in the Paperclip attribute. For example:

has_attached_file :picture,
  :url => "/system/:hash.jpg",
  :hash_secret => "long_secret_string",
  :storage => :s3,
  :s3_credentials => "#{Rails.root}/config/s3.yml"

Note that the :url is declared as '.jpg' rather than the traditional .:extension.

Good luck!

Upvotes: 0

yfeldblum
yfeldblum

Reputation: 65455

attachment = attachments.build(
  :attachment => File.open(tempfile.path)
)

# change the displayed file name stored in the db record here
attachment.attachment_file_name = a.filename # or whatever else you like

attachment.save!

Upvotes: 0

yfeldblum
yfeldblum

Reputation: 65455

You should use Paperclip's API for this:

tempfiles = []
attachments.each do |a|
  # use Attachment#to_file to get a :filesystem => file, :s3 => tempfile
  tempfiles << a.to_file
end

tempfiles.each do |tf|
  Rails.logger.debug tf.filename
end

Upvotes: 0

drummondj
drummondj

Reputation: 1483

The first argument for Tempfile.new is just a basename. To make sure each Tempfile is unique the characters are appended to the end of the file.

Upvotes: 4

Related Questions