Encode_www_form converts space to + instead of% 20

I am trying to create http parameters from a hash, I have Ruby on Rails, I tried to use it URI.encode_www_form(params), but this does not generate parameters correctly.

Below is the hash that 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 convert space with %20

I get "Name=Nia+Kun&AddressLine1=Address+One&City=City+Name", but I need these spaces to be converted to% 20

+4
source share
4 answers

You can do it as follows:

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

if this is really what you need.

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

+2
source

. - :

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

, params , url, .

EDIT:

:

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

encode_url(my_params)
+1

GSUB:

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

doc:

*, -,., 0-9, A-Z, _, a-z, SP ( ASCII) + % XX.

0

, , URI::escape.

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

:

  • params, with_indifferent_access. .
  • :

.

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"
0

Source: https://habr.com/ru/post/1609491/


All Articles