如何使用HTTParty gem与Rails5中的外部搜索API交互?

时间:2019-01-22 13:23:44

标签: ruby-on-rails ruby api httparty

如何在Rails中创建一个应用程序,让我输入搜索参数,然后将这些参数传递给外部API进行搜索,然后在我的应用程序中显示这些结果。我正在尝试使用HTTParty来实现这一目标,但我有点迷茫。我尝试在app / services中创建一个类方法,并在控制器中访问它,然后在我的视图中调用实例变量。目前,它引发了路由错误uninitialized constant ResultsController::Api。非常感谢您的帮助。

services / Api.rb

class Api
  include HTTParty
  base_uri "search.example.com"
  attr_accessor :name

  def initialize(name)
    self.name = name
  end

  def self.find(name)
    response = get("/results&q=#{name}")
    self.new(response["name"])
  end

results_controller.rb

class ResultsController < ApplicationController
  include Api

  def index
    @results = Api.find('test')
  end
end

路线:

Rails.application.routes.draw do
  resources :results
  root 'results#index'
end

1 个答案:

答案 0 :(得分:2)

您几乎是正确的,只需在此处进行一些更改。首先,将Api.rb重命名为api.rb-按照惯例,所有文件都应使用小蛇名命名。

class Api
  include HTTParty
  base_uri "http://search.spoonflower.com/searchv2"

  def find(name)
    self.class.get("/designs", query: { q: name }).parsed_response
  end
end

class ResultsController < ApplicationController    
  def index
    # here you get some json structure that you can display in the view
    @results = Api.new.find('test')['results']
  end
end