Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Permalink from post title (See related posts)

Method for permalink creation in ruby, based on drupal code

def create_permalink(string, separator = '-', max_size = 127)

    # words to ignore, usually the same words ignored by search engines
    ignore_words = ['a', 'an', 'the']
    ignore_re    = String.new
    
    # building ignore regexp
    ignore_words.each{ |word|
      ignore_re << word + '\b|\b'
    }
    ignore_re = '\b' + ignore_re + '\b'
    
    # replace apostrophes with separator
    permalink = string.gsub("'", separator)
    
    # delete ignore words
    permalink.gsub!(ignore_re, '')

    # all down
    permalink.downcase!

    # preserve alphanumerics, everything else becomes a separator
    permalink.gsub!(/[^a-z0-9]+/, separator)
    
    # enforce the maximum component length and return it
    permalink = permalink.to(max_size)
    
    # trim any leading or trailing separators
    return permalink.gsub(/^\\#{separator}+|\\#{separator}+$/, '')

end

Comments on this post

ismasan posts on Aug 24, 2007 at 16:16
Nice, but what about non-english accented characters? What about something like


require 'iconv'
class String
# Iconv use borrowed from http://svn.robertrevans.com/plugins/Permalize/
# Thanks!
def to_permalink
(Iconv.new('US-ASCII//TRANSLIT', 'utf-8').iconv self).gsub(/[^\w\s\-\—]/,'').gsub(/[^\w]|[\_]/,' ').split.join('-').downcase
end
end


It takes care of non-english characters and you can use it in any string, like: "Hello World".to_permalink #=> "hello-world".

You can add the ignored words and limit if you want, easily.
jerome posts on Aug 29, 2007 at 12:07
another way:


require 'unicode'
class String
def to_permalink
str = Unicode.normalize_KD(self).gsub(/[^\x00-\x7F]/n,'')
str = str.gsub(/[^-_\s\w]/, ' ').downcase.squeeze(' ').tr(' ','-').gsub(/-+$/,'')
end
end
</cide>

You need to create an account or log in to post comments to this site.


Click here to browse all 5137 code snippets

Related Posts