Module: Sluggify

Extended by:
ActiveSupport::Concern
Defined in:
lib/sluggify/version.rb,
lib/sluggify/sluggify.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.0.2"

Instance Method Summary collapse

Instance Method Details

#generate_slugObject



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

def generate_slug
  new_slug = self.send(self.class.slug_field).downcase.strip.gsub(/[\W]+/,"-")
  new_slug_base = new_slug 
  if self.class.exists?(:slug_base => new_slug_base)
    existing_slug = self.class.where(:slug_base => new_slug_base).sort(:created_at).last.slug
    if (existing_slug.split("-").last.to_i == 0)
      self.slug = new_slug + "-1"
    else
      new_slug_index = (existing_slug.split("-").last.to_i) + 1
      new_slug_index = new_slug_index.to_s
      self.slug = new_slug + "-" + new_slug_index
    end
  else
    self.slug = new_slug
  end
  self.slug_base = new_slug_base
end