在处理实务的时候,因为有幸碰到前人使用这样的写法,
一开始看到这样一串的时候,还真看得心慌慌:
url = "http://www.google.com"example_share_link = "https://lineit.line.me/share/ui?url=#{CGI.escape(url)}"
但其实还有更让人黑人问号的,例如这个:
url = "http://www.google.com"example_share_link = "https://lineit.line.me/share/ui?url=#{u url}"
所以我说,那个u
到底是干嘛的呢?
在没有任何提示下,除非本来就知道这个方法的由来,不然我想真的是查到怀疑人生。
先来介绍CGI.escape
The Common Gateway Interface (CGI) is a simple protocol for passing an HTTP request from a web server to a standalone program, and returning the output to the web browser. Basically, a CGI program is called with the parameters of the request passed in either in the environment (GET) or via $stdin (POST), and everything it prints to $stdout is returned to the client.
This file holds the CGI class. This class provides functionality for retrieving HTTP request parameters, managing cookies, and generating HTML output.
The file CGI::Session provides session management functionality; see that class for more details.
See www.w3.org/CGI/ for more information on the CGI protocol.
看起来实在有点冗长,容许我无法全部解释,一言以蔽之呢:
CGI is a large class, providing several categories of methods
而CGI.escape
就是使用 CGI 这个协议的方法。
escape(string):URL-encode a string.
原来就是针对 url 来做编码
的动作,使用上也很简单
来看一下操作的方式:
example_url = "http://www.google.com/"=> "http://www.google.com/"CGI.escape(example_url) => "http%3A%2F%2Fwww.google.com%2F"
这样对网址编码的动作就完成了~
再回头看一下#{u url}
,我想你们心里也有底了,其实这个方法也是拿来编码的
Also aliased as: u
而他的原型其实是url_encode()
这个方法
先来看一下说明:
A utility method for encoding the String s as a URL.
使用方法稍微繁琐一些:
require "erb"=> trueinclude ERB::Util=> Objectexample_url = "http://www.google.com/"=> "http://www.google.com/"url_encode(example_url)=> "http%3A%2F%2Fwww.google.com%2F"
发现与CGI.escape()
方法得到的结果看起来是一样的?
不过实际使用的时候,其实我更喜欢使用url_encode()
这个方法更多一点
会比较直观知道这个方法是做什么的,但如果用简称u
的话...,
我自己感觉是增加后人维护的难度,跟编码真的很难联想再一起。
最后自己还有两个疑问:
当字串含有空白的时候,其实会发现编码结果会有点不相同
example_string = "hello beauty!"CGI.escape(example_string)=> "hello+beauty%21"url_encode(example_string)=> "hello%20beauty%21"
两者编码方式对空白并不相同,不太清楚是为何~?
另一个则是,为什么会需要针对 url 做编码的动作呢?
分享出来,希望会有帮助需要的你~