Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct URI with query arguments from hash in Ruby

How to construct URI object with query arguments by passing hash?

I can generate query with:

URI::HTTPS.build(host: 'example.com', query: "a=#{hash[:a]}, b=#{[hash:b]}")

which generates

https://example.com?a=argument1&b=argument2

however I think constructing query string for many arguments would be unreadable and hard to maintain. I would like to construct query string by passing hash. Like in example below:

hash = {
  a: 'argument1',
  b: 'argument2'
  #... dozen more arguments
}
URI::HTTPS.build(host: 'example.com', query: hash)

which raises

NoMethodError: undefined method `to_str' for {:a=>"argument1", :b=>"argument2"}:Hash

Is it possible to construct query string based on hash using URI api? I don't want to monkey patch hash object...

like image 542
Filip Bartuzi Avatar asked Oct 21 '15 10:10

Filip Bartuzi


2 Answers

For those not using Rails or Active Support, the solution using the Ruby standard library is

hash = {
  a: 'argument1',
  b: 'argument2'
}
URI::HTTPS.build(host: 'example.com', query: URI.encode_www_form(hash))
=> #<URI::HTTPS https://example.com?a=argument1&b=argument2>
like image 122
Grizz Avatar answered Oct 22 '22 12:10

Grizz


If you have ActiveSupport, just call '#to_query' on hash.

hash = {
  a: 'argument1',
  b: 'argument2'
  #... dozen more arguments
}
URI::HTTPS.build(host: 'example.com', query: hash.to_query)

=> https://example.com?a=argument1&b=argument2

If you are not using rails remember to require 'uri'

like image 22
Filip Bartuzi Avatar answered Oct 22 '22 13:10

Filip Bartuzi