Как мне установить `base_uri` при использовании гема HTTParty? - PullRequest
0 голосов
/ 22 апреля 2019

Я создаю небольшой Rails, который использует внешний API геолокации. Нужно взять строку (адрес) и вернуть координаты. Я не уверен, как установить базовый URI с помощью гема HTTParty. Документация API гласит, что запросы могут быть отправлены на конечную точку

GET https://eu1.locationiq.com/v1/search.php?key=YOUR_PRIVATE_TOKEN&q=SEARCH_STRING&format=json

Как мне настроить токен и строку поиска в моем методе класса? Вот код, который у меня есть.

locationiq_api.rb

  include HTTParty
  base_uri "https://eu1.locationiq.com/v1/search.php?key=pk.29313e52bff0240b650bb0573332121e&q=SEARCH_STRING&format=json"

  attr_accessor :street

  def find_coordinates(street)
    self.class.get("/locations", query: { q: street })
  end

  def handle_error
    if find_coordinates.code.to_i = 200
      find_coordinates.parsed_response
    else
      raise "Couldn't connect to LocationIQ Api"
    end
  end
end```

locations controller:

```class LocationsController < ApplicationController
before_action :find_location, only: [:show, :destroy, :edit, :update]

def new
  @search = []
  # returns an array of hashes
  @search = locationiq_api.new.find_coordinates(params[:q])['results'] unless params[:q].nil?
end

def create
  @location = Location.new(location_params)
  if @location.save
    redirect_to root_path
  else
    render 'new'      
  end
end

private

  def location_params
    params.require(:location).permit(:place_name, :coordinate)
  end

  def find_location
    @location = Location.find(params[:id])
  end
end```

1 Ответ

0 голосов
/ 22 апреля 2019

Может помочь что-то подобное:

class LocationIqApi
  include HTTParty
  base_uri "https://eu1.locationiq.com/v1/search.php"

  def initialize(api_key, format = "json")
    @options = { key: api_key, format: format }
  end

  def find_coordinates(street)
    self.class.get("/locations", query: @options.merge({ q: street }))
  end

  def handle_error
    if find_coordinates.code.to_i = 200
      find_coordinates.parsed_response
    else
      raise "Couldn't connect to LocationIQ Api"
    end
  end
end

Затем, когда вы захотите использовать его, вам нужно будет создать новый экземпляр с вашим ключом:

@search = LocationIqApi.new(YOUR_API_KEY_HERE).find_coordinates(params[:q])
...