Sha256: 42a007bdcc7c6f352744ecf472cf2a7f95408eaa8ad4cbe5b28212c4b7d16cda

Contents?: true

Size: 1.43 KB

Versions: 1

Compression:

Stored size: 1.43 KB

Contents

module SuperSlug
  extend ActiveSupport::Concern

  included do
    after_save :sluggify_slug

    def self.find(input)
      if input.class == Array
        super
      else
        input.to_i.to_s == input.to_s ? super : find_by_slug(input)
      end
    end
  end

  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

  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.try(:idx)
        slug = "#{slug}-#{self.idx}"
      else
        slug = "#{slug}-#{self.id}"
      end
    end
    slug
  end

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

  def to_param
    slug
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
superslug-1.0.0 lib/superslug/superslug.rb