How to build a URI with request arguments from a hash in Ruby

How to build a URI object with request arguments by passing a hash?

I can generate a request 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 that building a query string for many arguments would be unreadable and difficult to maintain. I would like to build a query string by passing a hash. As in the 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 build a query string based on a hash using api uri? I do not want the monkey file hash object ...

+10
source share
2 answers

If you have ActiveSupport, just call '#to_query' for the 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 do not use rails, do not forget to require 'uri'

+13
source

For those who do not use Rails or Active Support, a solution using the standard Ruby library,

 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> 
+13
source

Source: https://habr.com/ru/post/1234186/


All Articles