在Ruby/Rails中,如何在URL中编码/转义特殊字符? [英] In Ruby/Rails, how can I encode/escape special characters in URLs?

查看:404
本文介绍了在Ruby/Rails中,如何在URL中编码/转义特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用OpenURI进行open(url)之前,如何编码或转义" URL?

How do I encode or 'escape' the URL before I use OpenURI to open(url)?

我们正在使用OpenURI打开远程URL并返回xml:

We're using OpenURI to open a remote url and return the xml:

getresult = open(url).read

问题是URL包含一些用户输入的文本,其中包含空格和其他字符,包括"+",&",?"等,因此,我们需要安全地转义URL.在使用Net :: HTTP时,我看到了很多示例,但没有为OpenURI找到任何示例.

The problem is the URL contains some user-input text that contains spaces and other characters, including "+", "&", "?", etc. potentially, so we need to safely escape the URL. I saw lots of examples when using Net::HTTP, but have not found any for OpenURI.

我们还需要能够转义从会话变量中收到的类似字符串,因此我们需要倒数功能.

We also need to be able to un-escape a similar string we receive in a session variable, so we need the reciprocal function.

推荐答案

Ruby具有内置的可寻址 gem,尤其是可寻址:: URI

Ruby has the built-in URI library, and the Addressable gem, in particular Addressable::URI

我更喜欢Addressable :: URI.它功能齐全,可以在使用query_values=方法时为您处理编码.

I prefer Addressable::URI. It's very full featured and handles the encoding for you when you use the query_values= method.

我已经看到一些有关URI的讨论,这些讨论正在经历越来越多的痛苦,因此我倾向于不理会URI,以便处理编码/转义,直到这些事情得到解决为止:

I've seen some discussions about URI going through some growing pains so I tend to leave it alone for handling encoding/escaping until these things get sorted out:

  • http://osdir.com/ml/ruby-core/2010-06/msg00324.html
  • http://osdir.com/ml/lang-ruby-core/2009-06/msg00350.html
  • http://osdir.com/ml/ruby-core/2011-06/msg00748.html

这篇关于在Ruby/Rails中,如何在URL中编码/转义特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆