Created
January 19, 2010 07:18
-
-
Save rajib/280743 to your computer and use it in GitHub Desktop.
generate_slug.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Post < ActiveRecord::Base | |
before_validation :generate_slug | |
def generate_slug | |
self.slug = self.title.dup if self.slug.blank? | |
self.slug.slugorize! | |
end | |
end | |
and in lib/core_extensions/string.rb | |
module CoreExtensions::String | |
def slugorize | |
result = self.downcase | |
result.gsub!(/&(\d)+;/, '') # Ditch Entities | |
result.gsub!('&', 'and') # Replace & with 'and' | |
result.gsub!(/['"]/, '') # replace quotes by nothing | |
result.gsub!(/\W/, ' ') # strip all non word chars | |
result.gsub!(/\ +/, '-') # replace all white space sections with a dash | |
result.gsub!(/(-)$/, '') # trim dashes | |
result.gsub!(/^(-)/, '') # trim dashes | |
result.gsub!(/[^a-zA-Z0-9\-]/, '-') # Get rid of anything we don't like | |
result | |
end | |
def slugorize! | |
self.replace(self.slugorize) | |
end | |
end | |
String.send(:include, CoreExtensions::String) | |
create initializer/ext.rb | |
require 'core_extensions/string' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment