Class: Slug
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- Slug
- Defined in:
- lib/friendly_id/slug.rb
Overview
A Slug is a unique, human-friendly identifier for an ActiveRecord.
Class Method Summary collapse
-
.normalize(slug_text) ⇒ Object
Sanitizes and dasherizes string to make it safe for URL’s.
- .parse(friendly_id) ⇒ Object
-
.strip_diacritics(string) ⇒ Object
Remove diacritics (accents, umlauts, etc.) from the string.
-
.strip_non_ascii(string) ⇒ Object
Remove non-ascii characters from the string.
Instance Method Summary collapse
-
#is_most_recent? ⇒ Boolean
Whether or not this slug is the most recent of its owner’s slugs.
- #to_friendly_id ⇒ Object
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.
26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/friendly_id/slug.rb', line 26 def normalize(slug_text) return "" if slug_text.nil? || slug_text == "" Unicode::normalize_KC(slug_text). send(chars_func). # For some reason Spanish ¡ and ¿ are not detected as non-word # characters. Bug in Ruby? gsub(/[\W|¡|¿]/u, ' '). strip. gsub(/\s+/u, '-'). gsub(/-\z/u, ''). downcase. to_s end |
.parse(friendly_id) ⇒ Object
40 41 42 43 44 |
# File 'lib/friendly_id/slug.rb', line 40 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.”
48 49 50 |
# File 'lib/friendly_id/slug.rb', line 48 def strip_diacritics(string) Unicode::normalize_KD(string).unpack('U*').select { |u| u < 0x300 || u > 0x036F }.pack('U*') end |
.strip_non_ascii(string) ⇒ Object
Remove non-ascii characters from the string.
53 54 55 |
# File 'lib/friendly_id/slug.rb', line 53 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.
66 67 68 |
# File 'lib/friendly_id/slug.rb', line 66 def is_most_recent? sluggable.slug == self end |
#to_friendly_id ⇒ Object
70 71 72 |
# File 'lib/friendly_id/slug.rb', line 70 def to_friendly_id sequence > 1 ? "#{name}--#{sequence}" : name end |