Search code examples
ruby-on-railsrubyurl-encoding

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?


Solution

  • 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.