LoginSignup
53
49

More than 5 years have passed since last update.

Hash からクエリ文字列を生成する

Posted at

ActiveSupport の Hash#to_param (もしくは Hash#to_query) を使えば
Hash から URL のクエリストリングの生成が簡単にできます。自前で key と value を連結して文字列を作るよりも安全ですしね。

require 'uri'
require 'active_support/core_ext'

# Google 画像検索 API 用の URL を生成する。
uri = URI("http://ajax.googleapis.com/ajax/services/search/images")
uri.query = {
  rsz: 8, v: 1.0, safe: "active", as_filetype: "gif", imgsz: "large",
  as_sitesearch: "tumblr.com", q: "ラブライブ!"
}.to_param
#=> "as_filetype=gif&as_sitesearch=tumblr.com&imgsz=large&q=%E3%83%A9%E3%83%96%E3%83%A9%E3%82%A4%E3%83%96%EF%BC%81&rsz=8&safe=active&v=1.0"
uri.to_s
#=> "http://ajax.googleapis.com/ajax/services/search/images?as_filetype=gif&as_sitesearch=tumblr.com&imgsz=large&q=%E3%83%A9%E3%83%96%E3%83%A9%E3%82%A4%E3%83%96%EF%BC%81&rsz=8&safe=active&v=1.0"
53
49
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
53
49