Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thomasklemm/87cf6618a0f734d70a98 to your computer and use it in GitHub Desktop.
Save thomasklemm/87cf6618a0f734d70a98 to your computer and use it in GitHub Desktop.
String#parameterize with preserve_case
ActiveSupport::Inflector.module_eval do
def parameterize(string, sep = '-', preserve_case: false)
# Overridden to allow for preserving the case with the preserve_case: true option
# Based on https://github.com/rails/rails/blob/5ea3f284a4d07f5572f7ae2a7442cca8761fa8fc/activesupport/lib/active_support/inflector/transliterate.rb#L81
# Replace accented chars with their ascii equivalents
parameterized_string = transliterate(string)
# Turn unwanted chars into the separator
parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
unless sep.nil? || sep.empty?
re_sep = Regexp.escape(sep)
# No more than one of the separator in a row.
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
# Remove leading/trailing separator.
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
end
parameterized_string.downcase! unless preserve_case
parameterized_string
end
end
String.class_eval do
def parameterize(sep = '-', **options)
# Overridden to allow for passing options to the ActiveSupport inflector
# Based on https://github.com/rails/rails/blob/7a8fb281d8563668991be55a64388c3e8b96249c/activesupport/lib/active_support/core_ext/string/inflections.rb#L167
ActiveSupport::Inflector.parameterize(self, sep, **options)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment