Replace umlaute (äüö) for SEO link in rails - best way

血红的双手。 提交于 2019-12-05 10:28:09
David Schmitt

Use String.gsub():

"ich bin doch nicht blöd, mann!".gsub(/[äöü]/) do |match|
    case match
        when "ä"
          'ae'
        when "ö"
          'oe'
        when "ü"
          'ue'
    end
end

Of course, the lookup can be improved by using a lookup table, but the principle should be clear.

Look at transliterate and parameterize (with transliterations in locales/de.yml):

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate

I18n.transliterate("Über der Höhenstraße")
 => "Ueber der Hoehenstrasse"

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize

"Über der Höhenstraße".parameterize
 => "ueber-der-hoehenstrasse"

If you don't want to write the transliterations yourself, you can install the rails-i18n gem.

I have written a small Library called Asciify for exactly that purpose

$ sudo gem install asciify

Usage:

#!/bin/ruby
require "asciify"

"Lücke".asciify   #=> "Luecke"

You can provide a YAML-file for custom mappings like so:

translator = Asciify.new("/path/to/mappings.yaml")
output_string = translator.convert("input string")

(see the builtin default mapping for the expected format)

The whole project is quite old, but maybe it does the job you need it to. If not, maybe the source code will be helpful.

Bijan
"äöü".gsub('ä','ae').gsub('ö','oe').gsub('ü','ue')

;)

Tomalak

I asked a similar question once. It was for JavaScript, and it takes a regex based aproach. Maybe the solution still carries some value for you, methodologically speaking.

steffen

Try using this: "Ich bin doch nicht böld ähhh ühh öhhh".gsub(/[äöüßÄÖÜ„“§%&–+]/){|t|t.to_xs}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!