Skip to content

How to: Upload from a string in Rails 3 or later

Pierre Pretorius edited this page Nov 11, 2015 · 1 revision

Rails 3 no longer provides a StringIO#original_filename method, so uploading files from a string doesn't work. For example, the following worked in Rails 2:

StringIO.new("foobar").original_filename # => "stringio.txt"

But in Rails 3, we see this error:

StringIO.new("foobar").original_filename NoMethodError: undefined method original_filename for StringIO

Quick and dirty solution:

s = StringIO.new("foobar")
def s.original_filename; "foobar.png"; end

Or do something like the following in a config/initializers/stringiohax.rb file.

class AppSpecificStringIO < StringIO
  attr_accessor :filepath

  def initialize(*args)
    super(*args[1..-1])
    @filepath = args[0]
  end

  def original_filename
    File.basename(@filepath)
  end
end

You can then do the following (or something similar) in your Model:

class DropboxFile < ActiveRecord::Base
  mount_uploader :attachment, AttachmentUploader

  def download(dropbox_session)
    file_as_string = dropbox_session.download(path)
    self.attachment = AppSpecificStringIO.new(path, file_as_string)
  end
end
Clone this wiki locally