2010-07-12 60 views
3

我需要在應用程序中支持國際化域名。更具體地說,我需要在將域名傳遞給外部API之前進行ACE編碼。Ruby - 國際化域名

做到這一點的最好方法似乎是使用libidn。然而,我在將它安裝到我的開發機器(Windows 7,ruby 1.8.6)時遇到問題,因爲它抱怨沒有找到GNU IDN庫(我已經安裝了它,並且還提供了完整路徑)。

所以基本上我正在考慮兩件事情:

  1. 搜索預建的Win32 libidn這個寶石網(至今無果而終)

  2. 查找另一(希望純)紅寶石庫,可以做同樣的事情(因爲我在這裏問這個問題沒有找到出色的表現)

所以你們有沒有人有libidn在Windows下工作?或者您是否使用了能夠對域名進行編碼的其他庫/代碼片段?

回答

3

感謝this snippet,我終於找到了一個不需要libidn的解決方案。它構建於punicode4r以及unicode gem(預構建二進制可以找到here)或ActiveSupport。我會使用ActiveSupport,因爲我使用Rails,但爲了參考,我包含了兩種方法。

隨着的Unicode寶石:

require 'unicode' 
require 'punycode' #This is not a gem, but a standalone file. 

    def idn_encode(domain) 
    parts = domain.split(".").map do |label| 
     encoded = Punycode.encode(Unicode::normalize_KC(Unicode::downcase(label))) 
     if encoded =~ /-$/ #Pure ASCII 
      encoded.chop! 
     else #Contains non-ASCII characters 
      "xn--" + encoded 
     end 
    end 
    parts.join(".") 
end 

隨着的ActiveSupport

require "punycode" 
require "active_support" 
$KCODE = "UTF-8" #Have to set this to enable mb_chars 

def idn_encode(domain) 
    parts = domain.split(".").map do |label| 
     encoded = Punycode.encode(label.mb_chars.downcase.normalize(:kc)) 
     if encoded =~ /-$/ #Pure ASCII 
      encoded.chop! #Remove trailing '-' 
     else #Contains non-ASCII characters 
      "xn--" + encoded 
     end 
    end 
    parts.join(".") 
end 

的的ActiveSupport溶液發現由於this StackOverflow的問題。

+0

對於它的價值,punycode模塊可作爲gem,在gemfile中使用: 'gem'punycode4r',require:'punycode'#internationalization of domain names' – phillbaker 2015-01-31 02:33:00