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. If your application uses these languages, check out this article for information on how to get better urls in your application.



35
36
37
38
39
40
41
42
43
44
# File 'lib/friendly_id/slug.rb', line 35

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



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

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.”



54
55
56
57
58
59
60
61
62
63
# File 'lib/friendly_id/slug.rb', line 54

def strip_diacritics(string)
  ActiveSupport::Multibyte.proxy_class.new(string).normalize(:kd).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.



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

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)


77
78
79
# File 'lib/friendly_id/slug.rb', line 77

def is_most_recent?
  sluggable.slug == self
end

#to_friendly_idObject



81
82
83
# File 'lib/friendly_id/slug.rb', line 81

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