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.

Constant Summary collapse

ASCII_APPROXIMATIONS =
{
  198 => "AE",
  208 => "D",
  216 => "O",
  222 => "Th",
  223 => "ss",
  230 => "ae",
  240 => "d",
  248 => "o",
  254 => "th"
}.freeze

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 the Unicode handling in ActiveSupport may fail to process some characters from Polish, Icelandic and other languages.



32
33
34
35
36
37
38
39
40
41
# File 'lib/friendly_id/slug.rb', line 32

def normalize(slug_text)
  return "" if slug_text.nil? || slug_text == ""
  ActiveSupport::Multibyte.proxy_class.new(slug_text.to_s).normalize(:kc).
    gsub(/[\W]/u, ' ').
    strip.
    gsub(/\s+/u, '-').
    gsub(/-\z/u, '').
    downcase.
    to_s
end

.parse(friendly_id) ⇒ Object



43
44
45
46
47
# File 'lib/friendly_id/slug.rb', line 43

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. Borrowed from “The Ruby Way.”



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/friendly_id/slug.rb', line 51

def strip_diacritics(string)
  a = ActiveSupport::Multibyte.proxy_class.new(string).normalize(:kd) || ""
  a.unpack('U*').inject([]) { |a, u|
    if ASCII_APPROXIMATIONS[u]
      a += ASCII_APPROXIMATIONS[u].unpack('U*')
    elsif (u < 0x300 || u > 0x036F)
      a << u
    end
    a
  }.pack('U*')
end

.strip_non_ascii(string) ⇒ Object

Remove non-ascii characters from the string.



66
67
68
# File 'lib/friendly_id/slug.rb', line 66

def strip_non_ascii(string)
  strip_diacritics(string).gsub(/[^a-z0-9]+/i, ' ')
end

Instance Method Details

#is_most_recent?Boolean

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

Returns:

  • (Boolean)


75
76
77
# File 'lib/friendly_id/slug.rb', line 75

def is_most_recent?
  sluggable.slug == self
end

#to_friendly_idObject



79
80
81
# File 'lib/friendly_id/slug.rb', line 79

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