opensource-developer
opensource-developer

Reputation: 3048

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

Upvotes: 8

Views: 3579

Answers (4)

vladra
vladra

Reputation: 186

You can write custom method. Something like this:

p = {x: 'some word', y: 'hello there'}
URI.encode p.to_a.map {|inner| inner.join('=') }.join('&')
# "x=some%20word&y=hello%20there"

So basically you flatten params to array of array, then transform them to url string, then encode it.

EDIT:

Final solution will look like this:

def encode_url(params)
  URI.encode params.to_a.map {|inner| inner.join('=')}.join('&')
end

encode_url(my_params)

Upvotes: 1

Max Alcala
Max Alcala

Reputation: 791

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"

Upvotes: 2

IngoAlbers
IngoAlbers

Reputation: 5802

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.

Upvotes: 6

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

You can use GSUB:

myString.gsub(" ", "%20")

Quoting the doc:

This method doesn't convert *, -, ., 0-9, A-Z, _, a-z, but does convert SP (ASCII space) to + and converts others to %XX.

Upvotes: 0

Related Questions