If I have this params for adding to the URL
params = { name: 'John Key' }
and use the method to_param
:
params.to_param
=> "name=John+Key"
The point is that '+' is not correctly read by the service used and is needed '%20' instead name=John%20Key
: When to encode space to plus (+) or %20?
Is there a way to return the params with '%20' without using gsub
?
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)
"#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
end
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
.
How about
URI.encode 'John Smith'
# => John%20Smith
not really.
Suggest using: your_params_hash.to_query.gsub("+", "%20")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With