aixecador
aixecador

Reputation: 876

Ruby API response - how to action

Learning Ruby & APIs. Practicing with the Uber API. Wrote a script to estimate the price of a ride.

require 'uber'
require 'geocoder'

def ride()

    # print "start? "
    # location_start = gets.chomp
    # print "finish? "
    # location_end = gets.chomp

    coordinates_start = Geocoder.coordinates("dublin") # gets a location for start and transforms into lat long
    coordinates_end = Geocoder.coordinates("dalkey") # gets a location for start and transforms into lat long

    client = Uber::Client.new do |config|
      config.server_token  = "{SERVER_TOKEN}"
      config.sandbox       = true
    end
    estimate = client.price_estimations(start_latitude: coordinates_start[0], start_longitude: coordinates_start[1],
                             end_latitude: coordinates_end[0], end_longitude: coordinates_end[1])
    estimate

end

puts ride

the output of estimate has the format #<Uber::Price:0x00007fc663821b90>. I run estimate.class and it's an array. I run estimate[0].class and I get Uber::Price. How can I extract the values that I should be getting from Uber's API response? [0]

[0] https://developer.uber.com/docs/riders/references/api/v1.2/estimates-price-get#response

Upvotes: 2

Views: 72

Answers (2)

kiddorails
kiddorails

Reputation: 13014

I am the maintainer and co-author of uber-ruby gem. @Schwern is correct, the client library gives the attributes same as that in uber api response's structure. I should probably indicate that in the documentation.

Please also note that test specs of the gem are 100% covered and it can give you the idea of how to interact with the gem, wherever it's unclear.

For price estimate, you can refer to https://github.com/AnkurGel/uber-ruby/blob/master/spec/lib/api/price_estimates_spec.rb#L61-L73

Upvotes: 2

Schwern
Schwern

Reputation: 164889

You're talking to the API via a library, normally you'd follow the documentation of that library uber-ruby.

Unfortunately that library doesn't document what an Uber::Price does. It's a safe guess that Uber::Price has the same fields as in the API documentation. Peaking at the code for Uber::Price we see this is basically correct.

attr_accessor :product_id, :currency_code, :display_name,
              :estimate, :low_estimate, :high_estimate,
              :surge_multiplier, :duration, :distance

You can access the API fields with estimate.field. For example, to see all estimates and durations...

estimates = ride()

estimates.each do |estimate|
    puts "Taking a #{estimate.display_name} will cost #{estimate.estimate} #{estimate.currency_code} and take #{estimate.duration / 60} minutes"
end

Upvotes: 3

Related Questions