2013-02-05 13:16:51 -06:00
|
|
|
# encoding: utf-8
|
|
|
|
|
|
|
|
module Slug
|
|
|
|
|
2016-10-12 14:44:26 -05:00
|
|
|
CHAR_FILTER_REGEXP = /[:\/\?#\[\]@!\$&'\(\)\*\+,;=_\.~%\\`^\s|\{\}"<>]+/ # :/?#[]@!$&'()*+,;=_.~%\`^|{}"<>
|
|
|
|
|
2015-04-13 09:50:41 -05:00
|
|
|
def self.for(string, default = 'topic')
|
2017-07-27 20:20:09 -05:00
|
|
|
slug =
|
|
|
|
case (SiteSetting.slug_generation_method || :ascii).to_sym
|
|
|
|
when :ascii then self.ascii_generator(string)
|
|
|
|
when :encoded then self.encoded_generator(string)
|
|
|
|
when :none then self.none_generator(string)
|
|
|
|
end
|
2015-04-13 09:50:41 -05:00
|
|
|
# Reject slugs that only contain numbers, because they would be indistinguishable from id's.
|
|
|
|
slug = (slug =~ /[^\d]/ ? slug : '')
|
|
|
|
slug.blank? ? default : slug
|
|
|
|
end
|
|
|
|
|
2015-05-13 03:52:48 -05:00
|
|
|
def self.sanitize(string)
|
|
|
|
self.encoded_generator(string)
|
|
|
|
end
|
|
|
|
|
2015-04-13 09:50:41 -05:00
|
|
|
private
|
|
|
|
|
|
|
|
def self.ascii_generator(string)
|
2016-06-10 21:37:33 -05:00
|
|
|
string.tr("'", "")
|
2017-07-27 20:20:09 -05:00
|
|
|
.parameterize
|
|
|
|
.tr("_", "-")
|
2013-02-05 13:16:51 -06:00
|
|
|
end
|
|
|
|
|
2015-04-13 09:50:41 -05:00
|
|
|
def self.encoded_generator(string)
|
2015-05-04 06:48:37 -05:00
|
|
|
# This generator will sanitize almost all special characters,
|
|
|
|
# including reserved characters from RFC3986.
|
|
|
|
# See also URI::REGEXP::PATTERN.
|
|
|
|
string.strip
|
2017-07-27 20:20:09 -05:00
|
|
|
.gsub(/\s+/, '-')
|
|
|
|
.gsub(CHAR_FILTER_REGEXP, '')
|
|
|
|
.gsub(/\A-+|-+\z/, '') # remove possible trailing and preceding dashes
|
|
|
|
.squeeze('-') # squeeze continuous dashes to prettify slug
|
2015-04-13 09:50:41 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.none_generator(string)
|
|
|
|
''
|
|
|
|
end
|
2013-02-05 13:16:51 -06:00
|
|
|
end
|