Ruby: Escape, Unescape, Encode, Decode, HTML, XML, URI, URL

江枫思渺然 提交于 2019-11-28 02:15:45

This example will show you how to escape and un-escape a value to be included in a URI and within HTML.

require 'cgi'

# escape
name = "ruby?"
value = "yes"
url = "http://example.com/?" + CGI.escape(name) + '=' + CGI.escape(value) + "&var=T"
# url: http://example.com/?ruby%3F=yes&var=T
html = %(<a href="#{CGI.escapeHTML(url)}">example</a>)
# html: <a href="http://example.com/?ruby%3F=yes&amp;var=T">example</a>

# unescape
name_encoded = html.match(/http:([^"]+)/)[0]
# name_encoded: http://example.com/?ruby%3F=yes&amp;var=T
href = CGI.unescapeHTML(name_encoded)
# href: http://example.com/?ruby%3F=yes&var=T
query = href.match(/\?(.*)$/)[1]
# query: ruby%3F=yes&var=T
pairs = query.split('&')
# pairs: ["ruby%3F=yes", "var=T"]
name, value = pairs[0].split('=').map{|v| CGI.unescape(v)}
# name, value: ["ruby?", "yes"]

转载于:https://www.cnblogs.com/feichan/archive/2012/04/11/ruby.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!