感謝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的問題。
對於它的價值,punycode模塊可作爲gem,在gemfile中使用: 'gem'punycode4r',require:'punycode'#internationalization of domain names' – phillbaker 2015-01-31 02:33:00