Skip to content

Instantly share code, notes, and snippets.

@sammylupt
Created October 8, 2013 12:46
Show Gist options
  • Save sammylupt/6884144 to your computer and use it in GitHub Desktop.
Save sammylupt/6884144 to your computer and use it in GitHub Desktop.
Reddit Grabber - refactor as objects
require 'json'
require 'rest_client'
class Story
attr_accessor :upvotes, :downvotes, :permalink, :title, :thumbnail, :over_18
@@stories = []
def initialize(post)
self.upvotes = post["data"]["ups"]
self.downvotes = post["data"]["downs"]
self.permalink = "http://www.reddit.com" + post["data"]["permalink"]
self.title = post["data"]["title"]
self.thumbnail = post["data"]["thumbnail"]
self.over_18 = post["data"]["over_18"]
@@stories << self
end
def template
"<li><a href='#{self.permalink}'><h1>#{self.title}</h1><img src='#{self.thumbnail}'/><h4>Upvotes:</h4><p>#{self.upvotes}</p><h4>Downvotes:</h4><p>#{self.downvotes}</p></a></li>"
end
def over_18?
self.over_18 == true
end
def self.all_stories
@@stories
end
end
class RedditGrabber
MAIN_PAGE = "http://reddit.com/.json"
OUTPUT = "output.html"
def initialize(options = {})
if options[:url]
@url = "http://reddit.com/r/" + options[:url] + ".json"
else
@url = MAIN_PAGE
end
@output = options[:output] || OUTPUT
end
def get_data
# Get the data from Reddit
# Convert each result into a Story
# Templatize that Story from the data
reddit_hash = JSON.parse(RestClient.get(@url))
@posts = reddit_hash["data"]["children"]
@posts = @posts.map { |post| Story.new(post) }
end
def write_to_file
combined = Story.all_stories.map { |story| story.template }.join
to_output = '<html><head></head><body><ul>' + combined + "</ul></body></html>"
output = File.open(@output, "w")
output << to_output
output.close
end
end
r = RedditGrabber.new
r.get_data
r.write_to_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment