【问题标题】:How do I set my `base_uri` when using the HTTParty gem?使用 HTTParty gem 时如何设置我的 `base_uri`?
【发布时间】:2019-04-22 17:42:44
【问题描述】:

我正在创建一个使用外部地理位置 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```

【问题讨论】:

    标签: ruby-on-rails ruby rest httparty


    【解决方案1】:

    这样的事情可能会有所帮助:

    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])
    

    【讨论】:

    • 当我尝试加载 http://localhost:3000/locations/new NameError in LocationsController#new uninitialized constant LocationsController::LocationIqApi 时出现错误
    • locationiq_api.rb 在哪里(例如,Rails 中的哪个文件夹)?可能是因为大写,所以这意味着自动加载没有启动 - 尝试调用类 LocationiqApi 来代替?
    • 它是应用程序/服务。根据您的示例,我已将其更改为 LocationIqApi,但仍然出现此错误。
    • 我需要类方法或类似的东西吗?似乎无法将我的手指放在它上面
    • 您可能需要明确要求该文件,除非您将应用程序/服务添加到您的自动加载路径(尽管根据您的 Rails 版本,这可能不需要):config.autoload_paths += [ Rails.root.join("app", "services") ]。如果你把它改成LocationIqApi,那么文件需要命名为location_iq_api.rb而不是locationiq_api.rb——文件名是Rails知道应该在那里定义常量的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多