1- class VideoService
1+ class VideoService
22 def video_list
3+ # NOTE: External service/Maybe
4+ video_list_json = File . read ( 'videos.json' )
35 # Read a json file and store the contents in an instance variable
4- @video_list = JSON . parse ( File . read ( 'videos.json' ) )
6+ @video_list = JSON . parse ( video_list_json )
57 # Get all the ids of the stored in the contents and JSON file that was just
68 ids = @video_list . map { |v | v [ 'youtubeID' ] }
79 # Get authorized with Google to be allowed to make API calls
10+ # NOTE: External Service
811 client = GoogleAuthorizer . new (
912 token_key : 'api-youtube' ,
1013 application_name : 'Gateway Youtube Example' ,
1114 application_version : '0.1'
1215 ) . api_client
1316 # Not sure what this does, but I think its a way to tell youtube what I'm asking for
17+ # NOTE: External Service
1418 youtube = client . discovered_api ( 'youtube' , 'v3' )
1519 # Send the request to Youtube passing in the ids of the videos from out Json file and telling which
1620 # data we want from youtube. We want a video snippet, contentDetails(probably a description)
1721 # and statistics about the video
1822 request = {
19- api_method : youtube . videos . list , # This looks like there are many api_methods and the one
23+ api_method : youtube . videos . list , # NOTE: External Service # This looks like there are many api_methods and the one
2024 # we are asking for is the one that returns a list of videos.
2125 parameters : {
2226 id : ids . join ( "," ) ,
2327 part : 'snippet, contentDetails, statistics' ,
2428 }
2529 }
2630 # Get the body of the response and parse it with JSON.parse to make into a Ruby hash
31+ # NOTE: External Service
2732 response = JSON . parse ( client . execute! ( request ) . body )
2833 # Go through the array of ids
29- ids . each do |id |
34+ ids . each do |id |
3035 # Find the video object that matches the this specific id
3136 video = @video_list . find { |v | id == v [ 'youtubeID' ] }
32- # Go through the items from the response and find one that matches the id
37+ # Go through the items from the response and find one that matches the id
3338 youtube_record = response [ 'items' ] . find { |v | id == v [ 'id' ] }
3439 # Update the views key in the video object(the one we got from our JSON file)
3540 # with the viewCount from the response we got from youtube.
3641 video [ 'views' ] = youtube_record [ 'statistics' ] [ 'viewCount' ] . to_i
3742 # Find out how many days the video has been live from the response from youtube
3843 days_available = Date . today - Date . parse ( youtube_record [ 'snippet' ] [ 'publishedAt' ] )
3944 # Update the monthly views of the video
40- video [ 'monthlyViews' ] = video [ 'views' ] * 365.0 / days_available / 12
45+ video [ 'monthlyViews' ] = video [ 'views' ] * 365.0 / days_available / 12
4146 end
4247 # return the updated video list in a JSON dump
4348 return JSON . dump ( @video_list )
4449 end
45- end
50+ end
0 commit comments