srm
srm

Reputation: 665

How to encode symbols using CGI::escape

I am using CGI::escape to encode symbols in a string, before I send the string as the parameters in a request.

It is working as expected with the '+' symbol, and CGI::escape('foo+bar') returns "foo%2Bbar" as expected.

However, I am running into problems with the '-' symbol. CGI::escape("2015-12-30") returns "2015-12-30". I was hoping for it to return "2015%2D12%2D30".

To add further context, I am making a request to an endpoint. In the specs for that endpoint they specify how they are expecting to receive the parameters. I have the base url and am adding parameters to the base url.

In the specs they require that the Date param '2015-12-30' be sent as "2015%2D12%2D30". That is why I need to encode the - symbol.

Upvotes: 1

Views: 1858

Answers (1)

the Tin Man
the Tin Man

Reputation: 160581

Use URI, not CGI:

require 'uri'

uri = URI.parse('http://www.example.com')
uri.query = URI::encode_www_form(
  'a' => '1+1',
  'b' => '/path/to/file',
  'c' => '2015-12-30'

)
uri.to_s 
# => "http://www.example.com?a=1%2B1&b=%2Fpath%2Fto%2Ffile&c=2015-12-30"

The - is valid and doesn't need to be encoded.

Upvotes: 1

Related Questions