public
Description: FriendlyId is the “Swiss Army bulldozer” of slugging and permalink plugins for ActiveRecord. It allows you to create pretty URL’s and work with human-friendly strings as if they were numeric ids for ActiveRecord models.
Homepage: http://friendly-id.rubyforge.org
Clone URL: git://github.com/norman/friendly_id.git
friendly_id / lib / slug.rb
100644 51 lines (46 sloc) 1.415 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# A Slug is a unique, human-friendly identifier for an ActiveRecord.
class Slug < ActiveRecord::Base
 
  belongs_to :sluggable, :polymorphic => true
  validates_uniqueness_of :name, :scope => :sluggable_type
  
   # Count exact matches for a slug. Matches include slugs with the same name
   # and an appended numeric suffix, i.e., "an-example-slug" and
   # "an-example-slug-2"
   #
   # The first two arguments are required, after which you may pass in the
   # same arguments as ActiveRecord::Base.find.
   def self.count_matches(slug_text, sluggable_type, *args)
    return 0 if !Slug.find_by_name(slug_text)
    slugs = with_scope({:find => {:conditions => ["name LIKE '#{slug_text}%' AND sluggable_type = ?",
        sluggable_type]}}) do
      find(*args)
    end
    count = 0
    slugs.each do |slug|
      count = count + 1 if slug.name =~ /\A#{slug_text}(-[\d]+)*\Z/
    end
    return count
  end
  
  # Whether or not this slug is the most recent of its owner's slugs.
  def is_most_recent?
    sluggable.slug == self
  end
  
  # Sanitizes and dasherizes string to make it safe for URL's.
  #
  # Example:
  #
  # This... is an example string!
  #
  # Becomes:
  #
  # this-is-an-example-string
  #
  def self.normalize(slug_text)
   s = slug_text.clone
   s.gsub!(/[\?‘’'“”",.;:]/, '')
   s.gsub!(/\W+/, ' ')
   s.strip!
   s.downcase!
   s.gsub!(/\s+/, '-')
   s.gsub(/-\Z/, '')
  end
  
end