Help us understand the problem. What is going on with this article?

ActiveSupportがない状況でもクエリパラメータを作る

More than 1 year has passed since last update.

Rubyでクエリパラメータを作る場合,大体の記事がActiveSupportの to_param を使っているのではないでしょうか.

このエントリではActiveSupportを様々な理由で入れたくないけれども,良い感じにクエリパラメータを作りたい場合に有効なサンプルコードを紹介します.

#!/usr/bin/env ruby

require 'net/http'
require 'uri'
require 'json'


APIID = ENV.fetch("APIID")
AFFIID = ENV.fetch("AffiliateID")

uri = URI('https://api.dmm.com/affiliate/v3/itemList')

uri.query = { api_id:  APIID,
              affiliate_id:  AFFIID,
              site:  "DMM.com",
              keyword: "魔法少女まどかマギカ"
}.map{ |key,val| "#{key.to_s}=#{val}"}.join('&')

json = Net::HTTP.get(uri)
res = JSON.parse(json)

主に
.map{ |key,val| "#{key.to_s}=#{val}"}.join('&') の部分で実行しています.
クエリパラメータは = の前後でkeyとvalがあるため,to_s でシンボルから文字列へとキャストし,クエリパラメータの並び順に文字列を設定します.
2つ目以降のクエリパラメータは & で連結していくため, join('&') などでつけてあげるといいでしょう.

追記

Rack::Utils#build_query を使っても同様のことが出来るようです! 教えていただきありがとうございます!

URIを使う

URI.encode_www_formでも良い感じに出来るようです!!!! やり方は色々ある!!!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした