1- class VideoService…
1+ class VideoService
22 def video_list
3+ # Read a json file and store the contents in an instance variable
34 @video_list = JSON . parse ( File . read ( 'videos.json' ) )
5+ # Get all the ids of the stored in the contents and JSON file that was just
46 ids = @video_list . map { |v | v [ 'youtubeID' ] }
7+ # Get authorized with Google to be allowed to make API calls
58 client = GoogleAuthorizer . new (
69 token_key : 'api-youtube' ,
710 application_name : 'Gateway Youtube Example' ,
811 application_version : '0.1'
912 ) . api_client
13+ # Not sure what this does, but I think its a way to tell youtube what I'm asking for
1014 youtube = client . discovered_api ( 'youtube' , 'v3' )
15+ # Send the request to Youtube passing in the ids of the videos from out Json file and telling which
16+ # data we want from youtube. We want a video snippet, contentDetails(probably a description)
17+ # and statistics about the video
1118 request = {
12- api_method : youtube . videos . list ,
19+ api_method : youtube . videos . list , # This looks like there are many api_methods and the one
20+ # we are asking for is the one that returns a list of videos.
1321 parameters : {
1422 id : ids . join ( "," ) ,
1523 part : 'snippet, contentDetails, statistics' ,
1624 }
1725 }
26+ # Get the body of the response and parse it with JSON.parse to make into a Ruby hash
1827 response = JSON . parse ( client . execute! ( request ) . body )
19- ids . each do |id |
28+ # Go through the array of ids
29+ ids . each do |id |
30+ # Find the video object that matches the this specific id
2031 video = @video_list . find { |v | id == v [ 'youtubeID' ] }
32+ # Go through the items from the response and find one that matches the id
2133 youtube_record = response [ 'items' ] . find { |v | id == v [ 'id' ] }
34+ # Update the views key in the video object(the one we got from our JSON file)
35+ # with the viewCount from the response we got from youtube.
2236 video [ 'views' ] = youtube_record [ 'statistics' ] [ 'viewCount' ] . to_i
37+ # Find out how many days the video has been live from the response from youtube
2338 days_available = Date . today - Date . parse ( youtube_record [ 'snippet' ] [ 'publishedAt' ] )
39+ # Update the monthly views of the video
2440 video [ 'monthlyViews' ] = video [ 'views' ] * 365.0 / days_available / 12
2541 end
42+ # return the updated video list in a JSON dump
2643 return JSON . dump ( @video_list )
2744 end
2845end
0 commit comments