ravmesser / responder-api-ruby

Ruby client for Responder API (רב מסר)
MIT License
0 stars 0 forks source link

Extract method #3

Open ynonp opened 5 years ago

ynonp commented 5 years ago

Hi,

I noticed there's almost no difference between the API methods, so it would look better to extract common code into a private method. For example instead of:

  def get_list(id)
    response = @access_token.request(:get, "/v1.0/lists?list_ids=" + id.to_s)
    rsp = JSON.parse(response.body)
    return rsp
  end

We should have:

def get_list(id)
  request("/lists?list_ids=#{id}")
end

Moreover you should use URI::encode on the value before using it to send a request as described here: https://ruby-doc.org/stdlib-2.5.1/libdoc/uri/rdoc/URI/Escape.html

itamardavidyan commented 5 years ago

I wrote this code:

  def sendRequest(type, object_name = "", query = "", args = {})
    if (!(args == {}) )
      json_obj = { object_name => 
        JSON.generate(args)
      }
    end

    query = URI.escape("/v1.0/lists" + query)
    response = @access_token.request(type, query, json_obj)
    response = JSON.parse(response.body) unless response.class == String
    return response
  end

But when I use URI.escape() or URI.encode() I got this warning: `sendRequest': warning: URI.escape is obsolete

ynonp commented 5 years ago

which ruby version are you using? You can also try:

https://docs.ruby-lang.org/en/2.2.0/URI.html#method-c-encode_www_form

Which encodes each part, so you'll write:

@access_token.request(:get, "/v1.0/lists?#{URI.encode_www_form('list_ids' => id)}")
itamardavidyan commented 5 years ago

ruby -v => ruby 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]

itamardavidyan commented 5 years ago

I fixed it by using URI.encode_www_form(). this is the new method:

  def send_request(type, object_name = '', path = '', query = [], args = {})
    unless args == {}
      json_obj = { object_name =>
        JSON.generate(args) }
    end

    path = '/v1.0/lists' + path
    query = [query]
    path_request = query.empty? ? path : path + URI.encode_www_form(query)
    response = @access_token.request(type, path_request, json_obj)
    response = JSON.parse(response.body) unless response.class == String
    response
  end