Module: Ardb::HasSlug::Slug

Defined in:
lib/ardb/has_slug.rb

Class Method Summary collapse

Class Method Details

.new(string, options = nil) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/ardb/has_slug.rb', line 85

def self.new(string, options = nil)
  options ||= {}
  preprocessor       = options[:preprocessor]
  separator          = options[:separator]
  allow_underscores  = options[:allow_underscores]
  regexp_escaped_sep = Regexp.escape(separator)

  slug = preprocessor.call(string.to_s.dup)
  # Turn unwanted chars into the separator
  slug.gsub!(/[^\w#{regexp_escaped_sep}]+/, separator)
  # Turn underscores into the separator, unless allowing
  slug.gsub!(/_/, separator) unless allow_underscores
  # No more than one of the separator in a row.
  slug.gsub!(/#{regexp_escaped_sep}{2,}/, separator)
  # Remove leading/trailing separator.
  slug.gsub!(/\A#{regexp_escaped_sep}|#{regexp_escaped_sep}\z/, '')
  slug
end