-1

I'm using Rubys rest-client gem to make a call to Google API and want to shorten the url part.

Current code:

class GoogleTimezoneGetter

  def initialize(lat:, lon:)
    @lat = lat
    @lon = lon
    @time_stamp = Time.new.to_i
  end

  def response
    response = RestClient.get "https://maps.googleapis.com/maps/api/timezone/json?location=#{@lat},#{@lon}&timestamp=#{@time_stamp}&key=#{GOOGLE_TIME_ZONE_KEY}"
    JSON.parse(response)
  end

  def time_zone
    response["timeZoneId"]
  end

end

I would like to be able to do something like:

def response
    response = RestClient.get (uri, params) 
    JSON.parse(response)
end 

But I'm struggling to find out how to do so.

To make the class a bit tidier, I'd like to break the url down into 'uri' and 'params'. I think the rest-client gem allows you to do this but I can't find specific examples.

I want to put the {@lat},#{@lon}&timestamp=#{@time_stamp}&key=#{GOOGLE_TIME_ZONE_KEY}" in to a 'params' method and pass that to the RestClient.get method.

Falko
  • 995
  • 11
  • 21
  • 1
    Can you elaborate in your question? get is already receiving an uri in your current code, and most probably optional params, which is nothing by now. – Sebastián Palma May 12 '19 at 17:23

2 Answers2

1

rest-client already accepts a hash for params. If you prefer a bunch of little methods on your class, you can divide out each step to a method and keep everything readable.

class GoogleTimezoneGetter

  def initialize(lat:, lon:)
    @lat = lat
    @lon = lon
    @time_stamp = Time.new.to_i
  end

  def response
    response = RestClient.get gtz_url, params: { gtz_params }
    JSON.parse(response)
  end

  def time_zone
    response["timeZoneId"]
  end

  def gtz_url
    "https://maps.googleapis.com/maps/api/timezone/json"
  end

  def gtz_params
    return {location: "#{@lat},#{@lon}", timestamp: @time_stamp, key: GOOGLE_TIME_ZONE_KEY }
  end
end
trh
  • 7,186
  • 2
  • 29
  • 41
1

Have you check the rest-client gem readme?

They did give a specific example on this (below example quoted from the readme)

RestClient.get 'http://example.com/resource', {params: {id: 50, 'foo' => 'bar'}}

In your case, it should be something like this

def url
  "https://maps.googleapis.com/maps/api/timezone/json"
end

def params
  {
    locations: "#{@lat},#{@lon}",
    timestamp: @time_stamp,
    key: GOOGLE_TIME_ZONE_KEY
  }
end

def response
  response = RestClient.get(url, params: params)
  JSON.parse(response)
end