【发布时间】:2014-05-22 08:04:02
【问题描述】:
我有 UTF-8 编码的帖子标题,我宁愿在 slug 中使用适当的字符来显示它们。一个例子是Amazon Japan's URL here。
如何使用 Ruby(或 Rails)将任意字符串转换为像这样的安全 URL slug?
【问题讨论】:
标签: ruby-on-rails ruby unicode sanitization slug
我有 UTF-8 编码的帖子标题,我宁愿在 slug 中使用适当的字符来显示它们。一个例子是Amazon Japan's URL here。
如何使用 Ruby(或 Rails)将任意字符串转换为像这样的安全 URL slug?
【问题讨论】:
标签: ruby-on-rails ruby unicode sanitization slug
从阅读here 看来,解决方案似乎是这样的:
require 'open-uri'
str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a".force_encoding('ASCII-8BIT')
puts URI::encode(str)
Here is the documentation for open-uri。和here is some info on utf-8 encoded url schema。
编辑:仔细研究后,我注意到 encode 只是 URI.escape 的别名,即 documented here。示例取自以下文档:
require 'uri'
enc_uri = URI.escape("http://example.com/?a=\11\15")
p enc_uri
# => "http://example.com/?a=%09%0D"
p URI.unescape(enc_uri)
# => "http://example.com/?a=\t\r"
p URI.escape("@?@!", "!?")
# => "@%3F@%21"
如果这就是你要找的东西,请告诉我?
编辑#2:我很感兴趣并继续看多一点,according to the commentsryan bates'railscasts on friendlyid 似乎也适用于汉字。
【讨论】: