Created
October 25, 2011 17:35
-
-
Save invisiblefunnel/1313597 to your computer and use it in GitHub Desktop.
Quick look at the HN front page via the ihackernews.com API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "net/http" | |
require "uri" | |
require "json" | |
class Story | |
@@stories = [] | |
@@endpoint = URI.parse("http://api.ihackernews.com/page") | |
@@fetched_at = nil | |
attr_accessor :title, :url, :id, :commentCount, :points, :postedAgo, :postedBy | |
def initialize(attrs={}) | |
for key in attrs.keys | |
method = "#{key}=".to_sym | |
send(method, attrs[key]) | |
end | |
@@stories << self | |
end | |
class << self | |
def fetch | |
if response = JSON.parse(Net::HTTP.get(@@endpoint)) | |
@@fetched_at = Time.now | |
response["items"].each { |item| new(item) } | |
end | |
true if fetched? | |
end | |
def fetched_at | |
@@fetched_at | |
end | |
def all | |
@@stories | |
end | |
def count | |
all.length | |
end | |
def at_rank(index) | |
all[index-1] | |
end | |
def find(id) | |
all.each { |story| return story if story.id == id } | |
end | |
def where(conds={}) | |
matches = [] | |
for story in all | |
match = true | |
for key in conds.keys | |
match = false unless story.send(key) == conds[key] | |
end | |
matches << story if match == true | |
end | |
matches | |
end | |
end | |
private | |
def self.fetched? | |
!!fetched_at | |
end | |
end | |
################# | |
# Example usage # | |
################# | |
Story.fetch | |
puts "total stories: #{Story.count}" | |
puts "fetched at: #{Story.fetched_at}" | |
puts "top story: #{Story.at_rank(1).title}" | |
puts "\n" | |
puts "max points: #{mp = Story.all.map(&:points).max}" | |
puts "story w/ max points: #{Story.where(:points => mp).first.title}" | |
puts "max comment count: #{mc = Story.all.map(&:commentCount).max}" | |
puts "story w/ max comment count: #{Story.where(:commentCount => mc).first.title}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment