Module: Slug

Extended by:
ActiveSupport::Concern
Defined in:
app/models/concerns/slug.rb

Instance Method Summary collapse

Instance Method Details

#create_slugObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'app/models/concerns/slug.rb', line 23

def create_slug
  slug = self.title.downcase.gsub(/\&/, ' and ') # & -> and
  slug.gsub!(/[^a-zA-Z0-9 \-]/, "") # remove all bad characters
  slug.gsub!(/\ /, "-") # replace spaces with underscores
  slug.gsub!(/\-+/, "-") # replace repeating underscores

  dups = self.class.name.constantize.where(:slug => slug)
  if dups.count == 1 and dups.first != self
    if self.idx.present?
      slug = "#{slug}-#{self.idx}"
    else
      slug = "#{slug}-#{self.id}"
    end
  end
  slug
end

#make_slug_unique(slug) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'app/models/concerns/slug.rb', line 40

def make_slug_unique(slug)
  dups = self.class.name.constantize.where(:slug => slug)
  if dups.count == 1 and dups.first != self
    if self.idx.present?
      slug = "#{slug}-#{self.idx}"
    else
      slug = "#{slug}-#{self.id}"
    end
  end
  slug
end

#sluggify_slugObject



12
13
14
15
16
17
18
19
20
21
# File 'app/models/concerns/slug.rb', line 12

def sluggify_slug
  if slug.blank?
    update_column(:slug, create_slug)
  else
    new_slug = slug.gsub(/[^a-zA-Z0-9 \-]/, "") # remove all bad characters
    new_slug.gsub!(/\ /, "-") # replace spaces with underscores
    new_slug.gsub!(/\-+/, "-") # replace repeating underscores
    update_column(:slug, new_slug) unless slug == new_slug
  end
end

#to_paramObject



52
53
54
# File 'app/models/concerns/slug.rb', line 52

def to_param
  slug
end