Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 212
AlexLarra Avatar asked Jul 13 '16 13:07

AlexLarra


3 Answers

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.

like image 126
Tom Lord Avatar answered Nov 02 '22 14:11

Tom Lord


How about

URI.encode 'John Smith'
# => John%20Smith
like image 41
OneChillDude Avatar answered Nov 02 '22 13:11

OneChillDude


not really.

Suggest using: your_params_hash.to_query.gsub("+", "%20")

like image 3
Blair Anderson Avatar answered Nov 02 '22 15:11

Blair Anderson