I am looking for a convenient and functional way to add encoded values to a URL query string in Ruby. Currently, I have:
require 'open-uri'
u = URI::HTTP.new("http", nil, "mydomain.example", nil, nil, "/tv", nil, "show=" + URI::encode("Rosie & Jim"), nil)
p u.to_s # => "http://mydomain.example/tv?show=Rosie%20&%20Jim"
This isn't what I'm looking for, because I need to get
"http://mydomain.example/tv?show=Rosie%20%26%20Jim"
, so that the show=
value is not truncated.
Does Open::URI have another method that would do this? If not, can it be done with any other standard Ruby, or gem?
Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.
Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing them into a URL.
A URL which contains a page on your site should NEVER have a "/" after it (e.g. "foo. html/") A URL should always have a single question mark in it "?" URL Query String parameters should be separated by the ampersand "&"
Try with CGI::escape
instead of URI::encode
. doc here
URI.encode_www_form
works well and is more convenient for adding multiple arguments
q = URI.encode_www_form("show" => "Rosie & Jim", "series" => "3", "episode" => "4")
u = URI::HTTP.new("http", nil, "mydomain.example", nil, nil, "/tv/ragdoll", nil, q, nil)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With