【问题标题】:Ruby - internationalized domain namesRuby - 国际化域名
【发布时间】:2010-07-12 09:12:32
【问题描述】:

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

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

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

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

  2. 找到另一个(希望是纯的)可以做同样事情的 ruby​​ 库(我在这里问这个问题时没有找到)

那么你们有没有人让 libidn 在 Windows 下工作?或者您是否使用过其他一些能够对域名进行编码的库/代码 sn-p?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    感谢this snippet,终于找到了不需要libidn的解决方案。它基于punicode4runicode 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 StackOverflow 问题,找到了 ActiveSupport 解决方案。

    【讨论】:

    • 对于它的价值,punycode 模块可以作为 gem 使用,在 gemfile 中:gem 'punycode4r', require: 'punycode' # internationalization of domain names
    猜你喜欢
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 2013-12-02
    • 2015-07-07
    • 1970-01-01
    相关资源
    最近更新 更多