Search code examples
ruby-on-railsrubyurimultibytehttparty

Ruby: how to represent multi-byte characters as percent-escaped octets for httparty consumption


I'm using HTTParty to get json data from some REST url

require 'httparty'

@search_term = "movies"
@data = HTTParty.get("http://api.douban.com/events?q=#{@search_term}")

The problem is if I pass a get parameter that contains multi-byte characters, for example if I wanted to use a Chinese UTF-8 search term, "电影":

@search_term = "电影"
@data = HTTParty.get("http://api.douban.com/events?q={@search_term")

I get an error

URI::InvalidURIError at / bad URI(is not URI?): link here

Searching on Stackoverflow, I found the following answer which suggest formatting my @search_term to percent-escaped octets, but I haven't been able to figure out how to do so.

I'm looking for a solution which would look like:

@search_term = params[:search_term]
@search_term = solution_with_some_escaping_or_something(@search_term)
@data = HTTParty.get("http://api.douban.com/events?q={@search_term")

#profit

Solution

  • I haven't tried it with non english characters.. but something like this should work.

    require 'cgi'
    
    @search_term = CGI::escape(@search_term)