module Sluggable

Public Instance Methods

append_suffix(str, count) click to toggle source
# File lib/sluggable_rockstar.rb, line 29
def append_suffix(str, count)
  if str.split('-').last.to_i != 0
    return str.split("-").slice(0...-1).join("-") + "-" + count.to_s
  else
    return str + "-" + count.to_s
  end
end
generate_slug!() click to toggle source
# File lib/sluggable_rockstar.rb, line 13
def generate_slug!
  new_slug = to_slug(self.send(self.class.slug_column.to_sym))

  # if a obj with this slug exists, uniquify it
  obj = self.class.find_by slug: new_slug

  count = 2
  while obj && obj != self
    new_slug = append_suffix(new_slug, count)
    obj = self.class.find_by slug: new_slug
    count += 1
  end

  self.slug = new_slug
end
to_param() click to toggle source
# File lib/sluggable_rockstar.rb, line 9
def to_param
  self.slug
end
to_slug(name) click to toggle source
# File lib/sluggable_rockstar.rb, line 37
def to_slug(name)
  str = name.strip.downcase
  str.gsub!(/\s*[^a-z0-9]\s*/, "-")
  str.gsub!(/-+/, "-")
  return str
end