Skip to content

Instantly share code, notes, and snippets.

@ftsanjuan
Created May 15, 2014 16:58
Show Gist options
  • Save ftsanjuan/2a64e38281a14cc2f07f to your computer and use it in GitHub Desktop.
Save ftsanjuan/2a64e38281a14cc2f07f to your computer and use it in GitHub Desktop.
Ruby String Extensions
# Extensions to the String class
class String
# converts a string to a symbol with spaces converted to underscores
def symbolize
self.downcase.gsub(/[^0-9A-Za-z ]/, '').gsub(" ", "_").to_sym
end
# converts a string to a machine-safe version
def machinize
self.downcase.gsub(/[^0-9A-Za-z ]/, '').gsub(" ", "_")
end
# converts a string with spaces/underscores to a hyphenated string
def hyphenize
self.downcase.gsub(/[^0-9A-Za-z _]/, '').gsub(/[ _]/, "-")
end
# converts a string to a filename safe version
# using hyphens in place of spaces
def filenamify
self.gsub(/[^0-9A-Za-z. ]/, '').gsub(" ", "-")
end
# converts a string to a filename safe version
# using hyphens in place of spaces and replacing encoded
# + character with an actual + (for Amazon S3 urls)
def s3_filenamify
self.gsub(/[^0-9A-Za-z. ]/, '').gsub("%2B", '+').gsub(" ", "-")
end
# converts a string to a model constant
def modelize
self.titleize.singularize.gsub(/[^0-9A-Za-z ]/, '').gsub(" ", "").constantize
end
# quick check to determine if a string is a number
# see: http://railsforum.com/viewtopic.php?id=19081
def number?
true if Float(self) rescue false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment