Class: Slug

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/friendly_id/slug.rb

Overview

A Slug is a unique, human-friendly identifier for an ActiveRecord.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.normalize(slug_text) ⇒ Object

Sanitizes and dasherizes string to make it safe for URL’s.

Example:

slug.normalize('This... is an example!') # => "this-is-an-example"

Note that Rails 2.2.x offers a parameterize method for this. It’s not used here because it assumes you want to strip away accented characters, and this may not always be your desire.

At the time of writing, it also handles several characters incorrectly, for instance replacing Icelandic’s “thorn” character with “y” rather than “d.” This might be pedantic, but I don’t want to piss off the Vikings. The last time anyone pissed them off, they uleashed a wave of terror in Europe unlike anything ever seen before or after. I’m not taking any chances.



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/friendly_id/slug.rb', line 25

def normalize(slug_text)
  return "" if slug_text.blank?
  slug_text.
    send(chars_func).
    # For some reason Spanish ¡ and ¿ are not detected as non-word
    # characters. Bug in Ruby?
    normalize.gsub(/[\W|¡|¿]/u, ' ').
    strip.
    gsub(/\s+/u, '-').
    gsub(/-\z/u, '').
    downcase.
    to_s
end

.parse(friendly_id) ⇒ Object



39
40
41
42
43
# File 'lib/friendly_id/slug.rb', line 39

def parse(friendly_id)
  name, sequence = friendly_id.split('--')
  sequence ||= "1"
  return name, sequence
end

.strip_diacritics(string) ⇒ Object

Remove diacritics (accents, umlauts, etc.) from the string.



46
47
48
49
50
51
# File 'lib/friendly_id/slug.rb', line 46

def strip_diacritics(string)
  require 'unicode'
  Unicode::normalize_KD(string).unpack('U*').select { |cp|
    cp < 0x300 || cp > 0x036F
  }.pack('U*')
end

Instance Method Details

#is_most_recent?Boolean

Whether or not this slug is the most recent of its owner’s slugs.

Returns:

  • (Boolean)


64
65
66
# File 'lib/friendly_id/slug.rb', line 64

def is_most_recent?
  sluggable.slug == self
end

#to_friendly_idObject



68
69
70
# File 'lib/friendly_id/slug.rb', line 68

def to_friendly_id
  sequence > 1 ? "#{name}--#{sequence}" : name
end