How to make a Ruby string safe for a filesystem?

filesystems, ruby, ruby-on-rails, string

Solution

From http://web.archive.org/web/20110529023841/http://devblog.muziboo.com/2008/06/17/attachment-fu-sanitize-filename-regex-and-unicode-gotcha/:

def sanitize_filename(filename)
  filename.strip.tap do |name|
   # NOTE: File.basename doesn't work right with Windows paths on Unix
   # get only the filename, not the whole path
   name.gsub!(/^.*(\\|\/)/, '')

   # Strip out the non-ascii character
   name.gsub!(/[^0-9A-Za-z.\-]/, '_')
  end
end

Problem

I have user entries as filenames. Of course this is not a good idea, so I want to drop everything except `[a-z]`, `[A-Z]`, `[0-9]`, `_` and `-`. For instance: ``` my§document$is°° very&interesting___thisIs%nice445.doc.pdf ``` should become ``` my_document_is_____very_interesting___thisIs_nice445_doc.pdf ``` and then ideally ``` my_document_is_very_interesting_thisIs_nice445_doc.pdf ``` Is there a nice and elegant way for doing this?

Original source

Related problems