Skip to content

Instantly share code, notes, and snippets.

@richcsmith
Created March 29, 2014 19:51
Show Gist options
  • Save richcsmith/9861637 to your computer and use it in GitHub Desktop.
Save richcsmith/9861637 to your computer and use it in GitHub Desktop.
Teddit API w/Mashable, Reddit and Digg
# We're going to add a remote data source to pull in stories from Mashable and Digg.
# http://mashable.com/stories.json
# http://digg.com/api/news/popular.json
# These stories will also be upvoted based on our rules. No more user input!
# Pull the json, parse it and then make a new story hash out of each story(Title, Category, Upvotes)
# Add each story to an array and display your "Front page"
require 'rest-client'
require 'json'
def welcome
puts "Welcome to Teddit! a text based news aggregator. Get today's news tomorrow!\n\n"
end
def calculate_upvotes(stories)
stories.each do |story|
if story[:category].include? 'cats'
story[:upvotes] *= 5
elsif (story[:category].include? 'Bacon') || (story[:category].include? 'bacon')
story[:upvotes] *= 8
else (story[:category].include? 'Food') || (story[:category].include? 'food')
story[:upvotes] *= 3
end
end
end
def show_all_stories(stories)
if stories.empty?
puts 'No stories yet!'
return
end
stories.each do |story|
if story[:category]
puts "Story: #{story[:title]}, Category: #{story[:category]}, Upvotes: #{story[:upvotes]}"
else
puts "Story: #{story[:title]}, Upvotes: #{story[:upvotes]}"
end
end
end
def get_from_reddit
puts "Getting stories from Reddit:"
stories = []
result = JSON.load RestClient.get('http://www.reddit.com/.json')
result['data']['children'].each do |json_story|
stories << {
title: json_story['data']['title'],
category: json_story['data']['subreddit'],
upvotes: json_story['data']['ups']
}
end
calculate_upvotes(stories)
show_all_stories(stories)
end
def get_from_mashable
puts "\n\nGetting stories from Mashable:"
stories = []
result = JSON.load RestClient.get('http://mashable.com/stories.json')
result['new'].each do |json_story|
if json_story['channel']
stories << {
title: json_story['title'],
category: json_story['channel'],
upvotes: json_story['shares']['total']
}
else
stories << {
title: json_story['title'],
upvotes: json_story['shares']['total']
}
end
end
calculate_upvotes(stories)
show_all_stories(stories)
end
def get_from_digg
puts "\n\nGetting stories from Digg:"
stories = []
result = JSON.load RestClient.get('http://digg.com/api/news/popular.json')\
result['data']['feed'].each do |json_story|
json_story['content']['tags'].each do |tag|
stories << {
title: json_story['content']['title_alt'],
category: tag['display'],
upvotes: json_story['diggs']['count']
}
end
end
calculate_upvotes(stories)
show_all_stories(stories)
end
welcome
get_from_reddit
get_from_mashable
get_from_digg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment