2017-01-19 7 views
0

Ruby on Railsフレームワークが初めてです。私はCourseraのRuby on Railsチュートリアルから、HTTPartyを使用してCoursera APIからいくつかのコースに関する情報を取得し、この情報を画面に表示しなければならなかった。しかし残念ながら私は問題に悩まされてしまった。ここでHTTParty 'get'はnilを返します:Ruby

はコーセラのAPIから情報を取得し、nilを返すGET「」は、なぜそれが

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

奇妙な。コースラがいつも同じ反応を返すとは限りません。

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

ご返信ありがとうございます。私はあなたのコードをテストしたし、私のシステムでは常に "Got Positive response"を与えています。それは良いですが、私のRailsアプリケーションでこのコードを呼び出すと、 "get"関数から返される "nil"が常に得られます。 (上記のコードで、いくつかのパラメータで "for"関数を呼び出すcoursera_controllerというコントローラがあります。ビューは、コントローラからの情報を取得し、画面上に表示します)。 –

関連する問題