LoginSignup
0
0

More than 3 years have passed since last update.

Ruby で URL を作るときのエスケープ処理

Last updated at Posted at 2020-11-16

https://xxxx といった文字列のURLに、 クエリパラメータをつけて URL を作る場合、 クエリパラメータは 特別な形に変換する必要があります。

JavaScript でいう encodeURIComponent を実行してやる必要があります。
これにより +%2B に、 &%26 になります。

基本

Ruby では CGI.escape を使います。

require 'cgi'

CGI.escape('+ &') # => "%2B+%26"

使用例

CGI.escape を使って URL を組み立ててみます。
ハッシュを使うなどいろいろと改善できるところはありますが、ここではシンプルなパターンを記載します。

"https://samole.com?key={CGI.escape(value)}"

key に特殊な文字を使うことはまずないと考えて value のみ escape をしています。

key も escape する場合は、
https://github.com/rails/rails/blob/3-0-stable/activesupport/lib/active_support/core_ext/object/to_query.rb が参考になります。

その他参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0