使用HTTParty gem时,如何设置我的`base_uri`?

时间:2019-04-22 17:42:44

标签: ruby-on-rails ruby rest httparty

我正在创建一个使用外部地理位置API的小型Rails。它应该使用一个字符串(地址)并返回坐标。我不确定如何使用HTTParty gem设置基本URI。该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 :(得分:0)

类似的事情可能会有所帮助:

$ipython
In [1]: import pandas as pd
    ...:
    ...: d = {'Fruit':["Melon", "Melon", "Melon", "Apple","Apple"],
    ...:  'Date':[203313, 414214, 511515,123223,501010]}
    ...: df = pd.DataFrame(d)
    ...:
    ...: df
    ...:
    ...:
Out[1]:
     Date  Fruit
0  203313  Melon
1  414214  Melon
2  511515  Melon
3  123223  Apple
4  501010  Apple

In [2]: idx = df.groupby(['Fruit'], sort=False)['Date'].transform(max) == df.Date

In [3]: df[idx]
Out[3]:
     Date  Fruit
2  511515  Melon
4  501010  Apple

然后,当您要使用它时,需要使用密钥创建一个新实例:

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