Format a string for use as a filename in Ruby

Posted on 20 October 2009

Often in Rails apps I want to take a string and use it for the filename of a document. Here's a method I use to extend the string class, I just put it inside a file in the /lib directory.

class String
  def to_filename
    result = self.downcase

    # Remove any non word chars
    result.gsub!(/\W/, ' ')

    # Convert spaces to dashes
    result.gsub!(/\  /, '-')

    # Trim dashes
    result.gsub!(/(-)$/, '')
    result.gsub!(/^(-)/, '')
   
    result = result[0..59]

    (result.blank?) ? Time.now.to_i : result
  end
end

Got something to say?