views:

248

answers:

2

Hi guys!

I'm trying to create permalink like behavior for some article titles and i don't want to add a new db field for permalink. So i decided to write a helper that will convert my article title from:

"O "focoasă" a pornit cruciada, împotriva bărbaţilor zgârciţi" to "o-focoasa-a-pornit-cruciada-impotriva-barbatilor-zgarciti".

While i figured out how to replace spaces with hyphens and remove other special characters (other than -) using:

title.gsub(/\s/, "-").gsub(/[^\w-]/, '').downcase

I am wondering if there is any other way to replace a character with a specific other character from only one .gsub method call, so I won't have to chain title.gsub("ă", "a") methods for all the UTF-8 special characters of my localization.

I was thinking of building a hash with all the special characters and their counterparts but I haven't figured out yet how to use variables with regexps.

What I was looking for is something like:

title.gsub(/\s/, "-").gsub(*replace character goes here*).gsub(/[^\w-]/, '').downcase

Thanks!

+3  A: 

I solved this in my application by using the Unidecoder gem:

require 'unidecode'

def uninternationalize(str)
  Unidecoder.decode(str).gsub("[?]", "").gsub(/`/, "'").strip
end
Daniel Vandersluis
Hi and thanks for the answer! after installing the gem i couldn't get it to work with require 'unicode' so i added config.gem 'unidecode', :version => '~> 1.0.0', :source => 'http://rubyforge.org' to my enviroment file.Then in the helper I just created the method and that was it!def permalink(title) Unidecoder.decode(title).gsub(/\s/, "-").gsub(/[^\w-]/, '').downcase end
If you were trying to require 'unicode', that would be your problem, the gem is 'unidecode' ;)
Daniel Vandersluis
Damn! you're right :) That's what i get for working this late. Thanks again!
+1  A: 
Jörg W Mittag