清理 URL slug 的 Unicode 字符串(Ruby/Rails)
Posted
技术标签:
【中文标题】清理 URL slug 的 Unicode 字符串(Ruby/Rails)【英文标题】:Sanitizing Unicode strings for URL slugs (Ruby/Rails) 【发布时间】:2014-05-22 08:04:02 【问题描述】:我有 UTF-8 编码的帖子标题,我宁愿在 slug 中使用适当的字符来显示它们。一个例子是Amazon Japan's URL here。
如何使用 Ruby(或 Rails)将任意字符串转换为像这样的安全 URL slug?
(有一些 related php 帖子,但我找不到 Ruby。)
【问题讨论】:
【参考方案1】:从阅读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 似乎也适用于汉字。
【讨论】:
谢谢。我将尝试在friendlyid 中试验核心功能。以上是关于清理 URL slug 的 Unicode 字符串(Ruby/Rails)的主要内容,如果未能解决你的问题,请参考以下文章