Skip to content

Instantly share code, notes, and snippets.

@khopkins218
Last active August 29, 2015 14:19
Show Gist options
  • Save khopkins218/9161ea088e8dc85ab974 to your computer and use it in GitHub Desktop.
Save khopkins218/9161ea088e8dc85ab974 to your computer and use it in GitHub Desktop.
NPR Story Puller with some OO
class Downloader
attr_accessor :stories, :selection
def initialize(selection = nil, stories)
self.stories = stories
self.selection = selection
end
def current_story
stories[selection - 1]
end
def exists?
selection > 0 && selection < stories.length
end
def exit?
selection == 0
end
def to_s
str = ''
stories.each_with_index do |story, index|
str += "#{index + 1}. #{story.title}\n"
end
str
end
end
require './npr_retriever'
require './story'
require './downloader'
puts "Welcome to the NPR Music Latest & Greatest\n\nThis program shows the last 20 stories on NPR Music with audio available for download, and lets you quickly download any of them.\n\nHere are the 20 most recent stories:"
downloader = Downloader.new(nil, Story.all)
puts downloader.to_s
while !downloader.exit?
puts "\nEnter the number of the audio file you'd like to download, or enter 0 to leave the program."
downloader.selection = gets.chomp.to_i
if downloader.exists?
system('open', downloader.current_story.audio_file)
elsif downloader.exit?
puts "Thanks for using NPR Music Latest & Greatest"
else
puts "\nSorry, that's not a valid selection."
end
end
require 'rest-client'
class NPRRetriever
API_KEY = 'MDE4ODc1MDMwMDE0MjkxNDI3MDc0NTgzNg001'
API_URL = "http://api.npr.org/query?id=10001&fields=title,teaser,audio,artist&requiredAssets=audio&dateType=story&sort=dateDesc&output=JSON&numResults=20&apiKey=#{API_KEY}"
def self.get_stories
JSON.parse(RestClient.get(API_URL))['list']['story']
end
end
class Story
attr_accessor :title, :audio_file
def initialize(attrs)
self.title = attrs['title']['$text']
self.audio_file = attrs['audio'].first['format']['mp3'].first['$text']
end
def self.all
stories = []
NPRRetriever.get_stories.map do |full_story|
stories << Story.new(full_story)
end
stories
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment