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

时光毁灭记忆、已成空白 提交于 2019-12-07 04:58:56

问题


I'm using the permalink_fu plugin to create permalinks from titles. My problem is: If the title contains german characters, they are just replaced with '_'.

What I need is something that replaces ä with ae ü with ue ö with oe

I fount String.tr but the problem here is that it replaces 1 character with 1 replacement, so it would work for replacing

é with e ø with o

etc.

Does anyone have a nice and clean solution for that?

Thanks


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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

;)




回答5:


Try String.sub!.




回答6:


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.




回答7:


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



来源:https://stackoverflow.com/questions/878789/replace-umlaute-%c3%a4%c3%bc%c3%b6-for-seo-link-in-rails-best-way

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