下記の課題に取り組むために事前学習
QiitaでWebAPI調査し、非公開記事にまとめています。
→ web apiの学習まとめ
その上で、下記課題に取り組んでいます。
解決したい課題
以下WebAPI3つ使って、ある「利用者ID」を与えて「利用者名」・「登録クラブ一覧」・「登録クラブポイント(point)」の出力プログラムをオブジェクト指向プログラミングで設計/実装しなさい。(URLは無効なURLです)
https://riko-19950120.herokuapp.com/users/1
json
1/*レスポンス(例)*/ 2 { 3 attributes: { 4 id: 1, 5 name: "Rico", 6 club_ids: [ 7 1, 8 3, 9 5 10 ] 11 } 12 }
https://riko-19950120.herokuapp.com/users/1/clubs
json
1 2/*レスポンス(例)*/ 3[ 4 { 5 attributes: { 6 id: 1, 7 user_id: 1, 8 name: "ライザップクラブ", 9 point: 15000 10 } 11 }, 12 { 13 attributes: { 14 id: 3, 15 user_id: 1, 16 name: "シックスパッドクラブ", 17 point: 13000 18 } 19 }, 20 { 21 attributes: { 22 id: 5, 23 user_id: 1, 24 name: "ゴールドジムクラブ", 25 point: 52000 26 } 27 } 28]
https://riko-19950120.herokuapp.com/clubs/2
json
1/*レスポンス(例)*/ 2{ 3 attributes: { 4 id: 2, 5 user_id: 2, 6 name: "ビリーズブートキャンプクラブ", 7 point: 2300 8 } 9}
自分なりの回答
require 'net/http' require 'openssl' require 'uri' require 'json' require 'logger' TIMEOUT_SECOND = 10 # HTTPSに使う時に必要??(今は横に置いておきました...。) # url = '' # https = Net::HTTP.new(url,443) # https.use_ssl = true # https.open_timeout = TIMEOUT_SECOND # https.read_timeout = TIMEOUT_SECOND # https.verify_mode = OpenSSL::SSL::VERIFY_PEER # https.verify_depth = 5 # Qiitaで見たメソッドをアレンジ) def get_json(location,limit=10) raise ArgumentError, 'too many HTTP redirects' if limit == 0 uri = URI.parse(location) begin response = Net::HTTP.start(uri.host,uri.port,use_ssl:uri.scheme == 'https') do |http| http.open_timeout = TIMEOUT_SECOND http.read_timeout = TIMEOUT_SECOND http.get(uri.request_uri) end case response when Net::HTTPSuccess json = response.body JSON.parse(json) ######## ここで「利用者名」・「登録クラブ一覧」・「登録クラブポイント(point)」を? #### when Net::HTTPRedirection location = response['location'] warn "redirected to #{location}" get_json(location, limit - 1) else puts [uri.to_s, response.value].join(" : ") # handle error end rescue => e puts [uri.to_s,e.class,e].join(":") end end puts get_json('****URL??****')
んー...色々まだ考えることがありそうです。。。
困っていること...。
わからないこと | |
---|---|
オブジェクト指向での実装 | オブジェクト志向の内容は理解をしていますが、プログラムに落とし込むことができていません。 |
設問の「ある『利用者ID』を与えて」...の文言 | 引数idをどのように与えるように実装すればよいのか。クラスのイニシャライズに与えるべきか、メソッドに与えるべきなのかわかりません。 |
ご助言頂ける方、よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/01/27 03:37