Ruby - Internationalized Domain Names

I need to support internationalized domain names in the application I am writing. In particular, I need ACE to encode domain names before passing them to the external API.

The best way to do this seems to be with libidn . However, I have problems installing it on my development machine (Windows 7, ruby ​​1.8.6), because it complains that it did not find the GNU IDN library (which I installed and also provided the full path).

So basically I am considering two things:

  • Internet search for pre-created win32 libidn gem (still fruitless)

  • Find another (hopefully clean) ruby ​​library that can do the same (not found, as I ask this question here)

So does any of you have libidn to run on Windows? Or did you use some other piece of library / code capable of encoding domain names?

+3
source share
1 answer

Thanks to this snippet , I finally found a solution that did not require libidn. It is built on punicode4r along with a unicode gem (a pre-generated binary can be found here ) or using ActiveSupport. I will use ActiveSupport, since I use Rails anyway, but for reference, I include both methods.

When using 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

With 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.

+3

Source: https://habr.com/ru/post/1754203/


All Articles