Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

encode_www_form converting space to + instead of %20

I am trying to create http parameters from a hash I have using Ruby on Rails, I have tried using URI.encode_www_form(params) , but this is not generating the parameters correctly.

Below is the hash I have

params['Name'.to_sym] = 'Nia Kun'
params['AddressLine1'.to_sym] = 'Address One'
params['City'.to_sym] = 'City Name'

This method converts space to +, what I want is it to convert space with %20

I am getting "Name=Nia+Kun&AddressLine1=Address+One&City=City+Name" but I need this spaces to be converted to %20

like image 280
opensource-developer Avatar asked Sep 29 '15 14:09

opensource-developer


2 Answers

You could do it like this:

URI.encode_www_form(params).gsub("+", "%20")

if that is really what you need.

See also When to encode space to plus (+) or %20? why it does it in this way.

like image 146
IngoAlbers Avatar answered Sep 23 '22 22:09

IngoAlbers


What you are looking for is URI::escape.

URI::escape "this big string"
=> "this%20big%20string"

EDIT

Bringing it all together:

  • You don't need to convert to symbols for your params, rails is smart and knows about with_indifferent_access. Strings and symbols will both work.
  • Your code would look like this:

.

name = params['Name']# = 'Nia Kun'
address_one = params['AddressLine1']# = 'Address One'
city = params['City']# = 'City Name'

URI::encode "http://www.example.com?name=#{name}&address_one=#{address_one}&city=#{city}"

#=> "http://www.example.com?name=Nia%20Kun&address_one=Address%20One&city=City%20Name"
like image 39
Max Alcala Avatar answered Sep 20 '22 22:09

Max Alcala