How to: Upload from a string in Rails 3

Chris Nelson edited this page Sep 6, 2016 · 11 revisions
Clone this wiki locally

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:"foobar").original_filename # => "stringio.txt"

But in Rails 3, we see this error:"foobar").original_filename NoMethodError: undefined method original_filename for StringIO

Quick and dirty solution:

StringIO.class_eval { def original_filename; "stringiohaxx.png"; end }

But, I'd much prefer not monkey patching the class in case another library is expecting it to behave as documented. To achieve this, I've most recently done something like the following in a config/initializers/stringiohax.rb file.

class AppSpecificStringIO < StringIO
  attr_accessor :filepath

  def initialize(*args)
    @filepath = args[0]

  def original_filename

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 =
    self.attachment =, file_as_string)