Skip to content

Commit

Permalink
String#slugorize now allows apostrophes, and correctly strips multiple
Browse files Browse the repository at this point in the history
dashes at the start and end of the string.
  • Loading branch information
xaviershay committed Nov 25, 2010
1 parent 4bdb37c commit 98cfaff
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 18 deletions.
30 changes: 16 additions & 14 deletions lib/core_extensions/string.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
module CoreExtensions::String
module CoreExtensions
module String

def slugorize
result = self.downcase
result.gsub!(/&([0-9a-z#])+;/, '') # Ditch Entities
result.gsub!('&', 'and') # Replace & with 'and'
result.gsub!(/[^a-z0-9\-]/, ' ') # Get rid of anything we don't like
result.gsub!(/\ +/, '-') # replace all white space sections with a dash
result.gsub!(/(-)$/, '') # trim dashes
result.gsub!(/^(-)/, '') # trim dashes
result.gsub!(/(-)+/, '-') # collapse dashes
result
end
def slugorize
result = self.downcase
result.gsub!(/&([0-9a-z#])+;/, '') # Ditch Entities
result.gsub!('&', 'and') # Replace & with 'and'
result.gsub!(/[^a-z0-9\-']/, '-') # Get rid of anything we don't like
result.gsub!(/-+/, '-') # collapse dashes
result.gsub!(/-$/, '') # trim dashes
result.gsub!(/^-/, '') # trim dashes
result
end

def slugorize!
self.replace(self.slugorize)
end

def slugorize!
self.replace(self.slugorize)
end
end

Expand Down
21 changes: 17 additions & 4 deletions spec/lib/slugorize_spec.rb
Original file line number Diff line number Diff line change
@@ -1,31 +1,44 @@
require 'spec_helper'

describe String do
describe String, '#slugorize' do
it "should lowercase everything" do
"ABCDEF".slugorize.should == "abcdef"
end

it "should leave alphanumerics and hyphens alone" do
"abc-123".slugorize.should == "abc-123"
end

it "should ditch entities" do
"abc<-<xyz".slugorize.should == "abc-xyz"
end

it "should replace & with and" do
"a-&-b-&-c".slugorize.should == "a-and-b-and-c"
end

it "should strip all non-alphanumeric characters except - and &" do
'abc\'""!@#$%^*()/=+|\[],.<>123'.slugorize.should == "abc-123"
'abc""!@#$%^*()/=+|\[],.<>123'.slugorize.should == "abc-123"
end

it "should allow apostrophes for good punctuation" do
"tomato's".slugorize.should == "tomato's"
end

it "should replace all whitespace with a dash" do
"abc\n\t xyz".slugorize.should == "abc-xyz"
end

it "should trim dashes at the tail" do
"abc-".slugorize.should == "abc"
"abc--".slugorize.should == "abc"
end

it "should trim dashes at the head" do
"-abc".slugorize.should == "abc"
"--abc".slugorize.should == "abc"
end

it "should collapse multiple dashes" do
"abc---xyz".slugorize.should == "abc-xyz"
end
end

0 comments on commit 98cfaff

Please sign in to comment.