From 9daf53df730c93c1732ca70e41cbe0dbbf993738 Mon Sep 17 00:00:00 2001 From: Dan Neumann Date: Mon, 11 Feb 2013 20:34:38 -0600 Subject: [PATCH 1/2] lean on Inflector transliteration --- lib/slug.rb | 11 ++++------- spec/components/slug_spec.rb | 6 ++++++ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/slug.rb b/lib/slug.rb index c4fe8fdfb0f..13dc53033eb 100644 --- a/lib/slug.rb +++ b/lib/slug.rb @@ -11,14 +11,11 @@ module Slug str.gsub!(/^\s+|\s+$/, '') str.downcase! - from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;." - to = "aaaaeeeeiiiioooouuuunc-------" + # The characters we want to replace with a hyphen + str.tr!("·/_,:;.", "\-") - idx = 0 - from.each_char do |c| - str.gsub!(c, to[idx]) - idx += 1 - end + # Convert to ASCII or remove if transliteration is unknown. + str = ActiveSupport::Inflector.transliterate(str, '') str.gsub!(/[^a-z0-9 -]/, '') str.gsub!(/\s+/, '-') diff --git a/spec/components/slug_spec.rb b/spec/components/slug_spec.rb index fde5ebd8e33..1390103cd3a 100644 --- a/spec/components/slug_spec.rb +++ b/spec/components/slug_spec.rb @@ -35,5 +35,11 @@ describe Slug do Slug.for("...hello").should == "hello" end + it 'handles our initial transliteration' do + from = "àáäâčďèéëěêìíïîľĺňòóöôŕřšťůùúüûýžñç" + to = "aaaacdeeeeeiiiillnoooorrstuuuuuyznc" + Slug.for(from).should == to + end + end From 50cf8cd4d56c1c7f42f6622975abbada4908db78 Mon Sep 17 00:00:00 2001 From: Dan Neumann Date: Mon, 11 Feb 2013 20:36:54 -0600 Subject: [PATCH 2/2] Set up slug.rb for obvious method extractions. --- lib/slug.rb | 16 ++++++++++------ spec/components/slug_spec.rb | 2 -- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/lib/slug.rb b/lib/slug.rb index 13dc53033eb..86025079c5f 100644 --- a/lib/slug.rb +++ b/lib/slug.rb @@ -6,20 +6,24 @@ module Slug def self.for(string) - - str = string.dup - str.gsub!(/^\s+|\s+$/, '') - str.downcase! - + str = string.dup.strip.downcase + # The characters we want to replace with a hyphen str.tr!("·/_,:;.", "\-") # Convert to ASCII or remove if transliteration is unknown. str = ActiveSupport::Inflector.transliterate(str, '') - + + # Remove everything except alphanumberic, space, and hyphen characters. str.gsub!(/[^a-z0-9 -]/, '') + + # Replace multiple spaces with one hyphen. str.gsub!(/\s+/, '-') + + # Replace multiple hyphens with one hyphen. str.gsub!(/\-+/, '-') + + # Remove leading and trailing hyphens str.gsub!(/^-|-$/, '') str diff --git a/spec/components/slug_spec.rb b/spec/components/slug_spec.rb index 1390103cd3a..44bd1177e8c 100644 --- a/spec/components/slug_spec.rb +++ b/spec/components/slug_spec.rb @@ -1,12 +1,10 @@ # encoding: utf-8 require 'spec_helper' - require 'slug' describe Slug do - it 'replaces spaces with hyphens' do Slug.for("hello world").should == 'hello-world' end