Expanding on Julie's answer to achieve the string of encoded values rather than a hash.
With the depreciation of URI.encode
it is possible to achieve this with ERB::Util.url_encode
, however you need to encode just the key and value pairs, not the full parameter, then join them together.
params = { name: 'John Key' }
# not what we want
ERB::Util.url_encode(params) # => "%7B%3Aname%3D%3E%22John%20Key%22%7D"
Here is a (pretty long) command that will work:
# Construct a new object (a string here) and build our params into it correctly.
# k = key of hash.
# v = value of hash.
# a = array created in each_with_object.
params.each_with_object([]) { |(k, v), a| a << [ERB::Util.url_encode(k), ERB::Util.url_encode(v)].join('=') }.join('&')
# => "name=John%20Key"
With more params:
params = { name: 'John Key', occupation: 'Web Developer!', 'Bad Key' => 'but works' }
params.each_with_object([]) { |(k, v), a| a << [ERB::Util.url_encode(k), ERB::Util.url_encode(v)].join('=') }.join('&')
# => "name=John%20Key&occupation=Web%20Developer%21&Bad%20Key=but%20works"
compared to Hash.to_query
params.to_query
# => "Bad+Key=but+works&name=John+Key&occupation=Web+Developer%21"