2013-02-06 03:16:51 +08:00
|
|
|
# encoding: utf-8
|
|
|
|
|
|
|
|
module Slug
|
|
|
|
|
2016-10-13 03:44:26 +08:00
|
|
|
CHAR_FILTER_REGEXP = /[:\/\?#\[\]@!\$&'\(\)\*\+,;=_\.~%\\`^\s|\{\}"<>]+/ # :/?#[]@!$&'()*+,;=_.~%\`^|{}"<>
|
|
|
|
|
2015-04-13 22:50:41 +08:00
|
|
|
def self.for(string, default = 'topic')
|
2015-05-06 06:50:54 +08:00
|
|
|
slug = case (SiteSetting.slug_generation_method || :ascii).to_sym
|
2015-04-13 22:50:41 +08:00
|
|
|
when :ascii then self.ascii_generator(string)
|
|
|
|
when :encoded then self.encoded_generator(string)
|
|
|
|
when :none then self.none_generator(string)
|
|
|
|
end
|
|
|
|
# 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 16:52:48 +08:00
|
|
|
def self.sanitize(string)
|
|
|
|
self.encoded_generator(string)
|
|
|
|
end
|
|
|
|
|
2015-04-13 22:50:41 +08:00
|
|
|
private
|
|
|
|
|
|
|
|
def self.ascii_generator(string)
|
2016-06-11 10:37:33 +08:00
|
|
|
string.tr("'", "")
|
2015-05-04 19:48:37 +08:00
|
|
|
.parameterize
|
2016-06-11 10:37:33 +08:00
|
|
|
.tr("_", "-")
|
2013-02-06 03:16:51 +08:00
|
|
|
end
|
|
|
|
|
2015-04-13 22:50:41 +08:00
|
|
|
def self.encoded_generator(string)
|
2015-05-04 19:48:37 +08:00
|
|
|
# This generator will sanitize almost all special characters,
|
|
|
|
# including reserved characters from RFC3986.
|
|
|
|
# See also URI::REGEXP::PATTERN.
|
|
|
|
string.strip
|
|
|
|
.gsub(/\s+/, '-')
|
2016-10-13 03:44:26 +08:00
|
|
|
.gsub(CHAR_FILTER_REGEXP, '')
|
2015-05-04 19:48:37 +08:00
|
|
|
.gsub(/\A-+|-+\z/, '') # remove possible trailing and preceding dashes
|
|
|
|
.squeeze('-') # squeeze continuous dashes to prettify slug
|
2015-04-13 22:50:41 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.none_generator(string)
|
|
|
|
''
|
|
|
|
end
|
2013-02-06 03:16:51 +08:00
|
|
|
end
|