2017-01-19 10 views
0

Ruby on Rails 프레임 워크를 처음 사용했습니다. 나는 Coursera API에서 HTTParty를 사용하여 일부 코스에 대한 정보를 얻고이 정보를 화면에 표시해야하는 coursera에 대한 Ruby on Rails 자습서에서 연습 연습을하고있었습니다. 그러나 불행히도 나는 문제에 갇혀있다. HTTParty 'get'은 nil을 반환합니다. Ruby

다음은 코 세라의 API에서 정보를 가져옵니다하고

class Coursera 
    include HTTParty 

    base_uri 'https://api.coursera.org/api/catalog.v1/courses' 
    default_params fields: "smallIcon,shortDescription", q: "search" 
    format :json 

    def self.for term 
     response=get("", query: { query: term})["elements"] 
     if(response==nil) 
      puts "Got Negative response!" 
     else 
      puts "Got Positive response!" 
      return response 
     end 
    end 
end 

누군가가 왜 '수'전무를 반환 지적 할 수 반환 내 코드입니다. 나는 실수를 저지르고 있지만 누군가 그것을 지적 할 수있을 것이라고 확신한다. 미리 감사드립니다.

+1

내가 기본'HTTParty.get (...)에 코드를 줄여 보시기 바랍니다 [ '요소'] '작동 한 다음 다시 깨질 때까지 앞으로 움직입니다. –

답변

0

이상한. coursera가 항상 동일한 응답을 반환하지 않는 것 같습니다.

require 'httparty' 

class Coursera 
    include HTTParty 

    base_uri 'https://api.coursera.org/api/catalog.v1/courses' 
    default_params fields: "smallIcon,shortDescription", q: "search" 
    format :json 

    def self.for term 
    response = get("", query: {query: term}) 
    puts response.request.last_uri.to_s 
    elements = response["elements"] 
    if elements 
     puts "Got Positive response!" 
     response 
    else 
     puts "Got Negative response!" 
    end 
    end 
end 

p Coursera.for 'python' 

때때로 반환 : 때때로

https://api.coursera.org/api/catalog.v1/courses?fields=smallIcon%2CshortDescription&q=search&query=python 
Got Negative response! 
nil 

과 :

https://api.coursera.org/api/catalog.v1/courses?fields=smallIcon%2CshortDescription&q=search&query=python 
Got Positive response! 
#<HTTParty::Response:0x2660970 parsed_response={"elements"=>[{"id"=>119, "shortName"=>"scicomp", "name"=>"High Performance Scientific Computing", "shortDescription"=>"Programming-oriented course on effectively using modern computers to solve scientific computing problems arising in the physical/engineering sciences and other fields. Provides an introduction to efficient serial and parallel computing using Fortran 90, OpenMP, MPI, and Python, and software development tools such as version control, Makefiles, and debugging.", "smallIcon"=>"https://d15cw65ipctsrr.cloudfront.net/00/621b9b2597807229ed0fa605f96cdc/HighPerformanceComputingIma.jpg", "links"=>{}}, {"id"=>87, "shortName"=>"compphoto", "name"=>"Computational Photography", "shortDescription"=>"In this course you will learn about the basics of 
.... 
+0

다른 사이트에서 발생하는 것을 보았습니다. 내 생각 엔 항상로드 밸런서 뒤에 있고 모든 컴퓨터를 동일한 버전으로 업데이트하지 않았던 것 같습니다. 기본적으로 호스트에 불일치가 있습니다. –

+0

답장을 보내 주셔서 감사합니다. Eric. 나는 당신의 코드를 테스트했으며, 내 시스템에는 항상 "긍정적 인 반응을 얻었습니다."라고 나와 있습니다. 좋습니다.하지만 문제는 레일즈 애플리케이션에서이 코드를 호출 할 때 "get"함수가 반환 한 "nil"을 항상 얻는 것입니다. (위의 코드에서 "for"함수를 호출하는 coursera_controller라는 컨트롤러가 있습니다. 컨트롤러에서 정보를 가져 와서 화면에 표시합니다.) –