Module UrlKey
In: vendor/plugins/url_key/lib/url_key.rb

Use this in your ActiveRecord models with has_url_key :attr_name. You must add a column for storing the URL key. This defaults to url_key.

Methods

Public Class methods

Given str, the url_key_field and the ActiveRecord class klass, create a unique URL key.

[Source]

    # File vendor/plugins/url_key/lib/url_key.rb, line 20
20:     def create_url_key(str, url_key_field, klass)
21:       str = UrlKey.escape(str)
22:       key = str
23:       counter = 1
24:       until klass.find(:all, :conditions => ["#{url_key_field} = ?", key]).empty?
25:         key = "#{str}-#{counter}"
26:         counter += 1
27:       end
28:        
29:       key
30:     end

Escape str by transliterating to ASCII with Iconv, downcasing, then removing illegal characters and replacing them with ’-’

[Source]

    # File vendor/plugins/url_key/lib/url_key.rb, line 8
 8:     def escape(str)
 9:       s = Iconv.iconv('ascii//ignore//translit', 'utf-8', str).to_s
10:       s = s.downcase
11:       s = s.gsub(/\W+/, ' ')
12:       s = s.strip
13:       s = s.gsub(/\ +/, '-') # set single or multiple spaces to a single dash
14:       
15:       return s
16:     end

Public Instance methods

Call this in your model with the name of the attribute to base the URL key on, and optionally the name of the URL key field. (defaults to url_key)

[Source]

    # File vendor/plugins/url_key/lib/url_key.rb, line 36
36:   def has_url_key(attr_name, url_key_field = nil)
37:     url_key_field ||= 'url_key'
38:     before_validation_on_create { |record|
39:       key = UrlKey.create_url_key(record.send(attr_name).to_s, 
40:                                   url_key_field,
41:                                   record.class)
42:                   
43:       record.send("#{url_key_field}=", key) 
44:     }
45:   end

[Validate]