AlexLarra AlexLarra - 1 year ago 50
Ruby Question

How to get params for url with whitespace as '%20' instead of '+' in Rails

If I have this params for adding to the URL

params = { name: 'John Key' }

and use the method

=> "name=John+Key"

The point is that '+' is not correctly read by the service used and is needed '%20' instead
: When to encode space to plus (+) or %20?

Is there a way to return the params with '%20' without using

Answer Source

I would recommend just sticking to the use of a gsub, perhaps with a comment to explain the need for such behaviour.

While you could solve the problem by use of URI.escape, it is supposedly deprecated, as it does not fully conform to RFC specs. See here for a great write-up on it.

Hash#to_param is an alias of Hash#to_query, which calls Object#to_query. The simplest example to demonstrate this + vs %20 issue is:

'John Key'.to_query(:name) # => "name=John+Key"

The implementation of Object#to_query is:

def to_query(key)

And so, we find that:

CGI.escape("John Key") # => "John+Key"

Hence, this is why I have referenced the differences between CGI.escape and URI.escape.