iT邦幫忙

0

CGI.escape V.S url_encode in Ruby村

在處理實務的時候,因為有幸碰到前人使用這樣的寫法,
一開始看到這樣一串的時候,還真看得心慌慌:

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"
=> true
include ERB::Util
=> Object
example_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 做編碼的動作呢?
分享出來,希望會有幫助需要的你~


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言