Skip to content

Instantly share code, notes, and snippets.

@blairanderson
Created January 9, 2022 03:59
Show Gist options
  • Save blairanderson/687e4d61e7dd8dd729d78b43ff0346e6 to your computer and use it in GitHub Desktop.
Save blairanderson/687e4d61e7dd8dd729d78b43ff0346e6 to your computer and use it in GitHub Desktop.
rails / ruby parameterize
class String
def parameterize(separator: "-")
# Turn unwanted chars into the separator.
self.gsub!(/[^a-z0-9\-_]+/i, separator)
unless separator.nil? || separator.empty?
if separator == "-"
re_duplicate_separator = /-{2,}/
re_leading_trailing_separator = /^-|-$/i
else
re_sep = Regexp.escape(separator)
re_duplicate_separator = /#{re_sep}{2,}/
re_leading_trailing_separator = /^#{re_sep}|#{re_sep}$/i
end
# No more than one of the separator in a row.
self.gsub!(re_duplicate_separator, separator)
# Remove leading/trailing separator.
self.gsub!(re_leading_trailing_separator, "")
end
self.downcase!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment