discourse/lib/slug.rb

45 lines
1.3 KiB
Ruby
Raw Normal View History

2013-02-05 14:16:51 -05:00
# encoding: utf-8
module Slug
CHAR_FILTER_REGEXP = /[:\/\?#\[\]@!\$&'\(\)\*\+,;=_\.~%\\`^\s|\{\}"<>]+/ # :/?#[]@!$&'()*+,;=_.~%\`^|{}"<>
2015-04-13 10:50:41 -04:00
def self.for(string, default = 'topic')
slug = case (SiteSetting.slug_generation_method || :ascii).to_sym
2015-04-13 10:50:41 -04: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
def self.sanitize(string)
self.encoded_generator(string)
end
2015-04-13 10:50:41 -04:00
private
def self.ascii_generator(string)
string.tr("'", "")
.parameterize
.tr("_", "-")
2013-02-05 14:16:51 -05:00
end
2015-04-13 10:50:41 -04:00
def self.encoded_generator(string)
# This generator will sanitize almost all special characters,
# including reserved characters from RFC3986.
# See also URI::REGEXP::PATTERN.
string.strip
.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 10:50:41 -04:00
end
def self.none_generator(string)
''
end
2013-02-05 14:16:51 -05:00
end