gpt4 book ai didi

Ruby——国际化域名

转载 作者:数据小太阳 更新时间:2023-10-29 08:02:05 24 4
gpt4 key购买 nike

我需要在我编写的应用程序中支持国际化域名。更具体地说,我需要先对域名进行 ACE 编码,然后再将它们传递给外部 API。

最好的方法似乎是使用 libidn .但是,我在我的开发机器(Windows 7,ruby 1.8.6)上安装它时遇到问题,因为它提示找不到 GNU IDN 库(我已经安装了它,并且还提供了完整路径)。

所以基本上我在考虑两件事:

  1. 在网络上搜索预构建的 win32 libidn gem(到目前为止没有结果)

  2. 找到另一个(希望是纯的)ruby 库,它可以做同样的事情(没有找到合适的,因为我在这里问这个问题)

所以你们中有人得到了在 Windows 下工作的 libidn 吗?或者您是否使用了其他能够对域名进行编码的库/代码片段?

最佳答案

感谢this snippet ,我终于找到了一个不需要libidn的解决方案。它建立在 punicode4r 之上连同 unicode gem(可以找到预构建的二进制文件 here ),或使用 ActiveSupport。我将使用 ActiveSupport,因为无论如何我都使用 Rails,但为了引用,我包括了这两种方法。

使用 unicode gem:

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

感谢 this 找到了 ActiveSupport 解决方案StackOverflow 问题。

关于Ruby——国际化域名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3227126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com