Module: Sluggable

Extended by:
ActiveSupport::Concern
Defined in:
lib/sluggable_pb.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#generate_slug!Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/sluggable_pb.rb', line 9

def generate_slug!
  return if self.slug
  
  new_slug = to_slug(self.send(self.class.slug_column.to_sym))
  last_char = new_slug[-1]
  
  while self.class.find_by(slug: new_slug)
    if last_char.to_i == 0
      new_slug += "-" + (last_char.to_i + 1).to_s
    else
      next_num = last_char.to_i + 1
      new_slug[-1] = next_num.to_s
    end
  end
  self.slug = new_slug
end

#to_paramObject



33
34
35
# File 'lib/sluggable_pb.rb', line 33

def to_param
  self.slug
end

#to_slug(name) ⇒ Object



26
27
28
29
30
31
# File 'lib/sluggable_pb.rb', line 26

def to_slug(name)
  slugged = name.gsub(/[\s[^a-zA-Z0-9]]/, "-")
  slugged.gsub!(/-{2,}/, "-")
  slugged.gsub!(/\A-+|-+\z/, "")
  slugged.downcase
end