Skip to content

Instantly share code, notes, and snippets.

@mkroman
Created September 25, 2010 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkroman/905f499106d5a8a63e9e to your computer and use it in GitHub Desktop.
Save mkroman/905f499106d5a8a63e9e to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'sinatra'
require 'service'
root_dir = ::File.dirname(__FILE__)
set :environment, ENV['RACK_ENV'].to_sym
set :app_file, ::File.join(root_dir, 'service.rb')
set :root, root_dir
disable :run
run Sinatra::Application
#!/usr/bin/env ruby
# encoding: utf-8
require 'json'
require 'sinatra'
require 'open-uri'
require 'datamapper'
Reddit = 'http://www.reddit.com'
Database = "/var/www/applications/reverse_reddit/reddit.db"
Thread.abort_on_exception = true
DataMapper.setup :default, "sqlite3://#{Database}"
class Submission
include DataMapper::Resource
property :id, Serial
property :url, Text
property :name, Text
property :nsfw, Boolean
property :subreddit, String
property :permalink, Text
def self.create_from_json json
new.tap do |this|
this.url = json['url']
this.name = json['title']
this.nsfw = json['over_18']
this.subreddit = json['subreddit']
this.permalink = json['permalink']
end.save
end
def to_json
{
url: url,
nsfw: nsfw,
title: name,
status: 200,
subreddit: subreddit,
permalink: permalink
}.to_json
end
end
# 1. a person who has the charge or care of something, esp a building, or someone
class Warden
def self.work
Warden.new do |warden|
loop do
warden.patrol and sleep 30 # bacon
end
end
end
def initialize
yield self if block_given?
end
def patrol
open "#{Reddit}/r/all/new.json?sort=new" do |response|
json = JSON.parse response.read
json['data']['children'].each do |submission|
data = submission['data']
if not Submission.first permalink: data['permalink']
if Submission.create_from_json data
puts "==> new submission: #{data['title'].inspect} ..."
end
end
end
end
end
end
# Preload the database
DataMapper.auto_upgrade!
# Let the Warden work in the background
Thread.new &Warden.method(:work)
# /reverse?url=<url>
get '/reverse' do
if not params[:url]
{ status: 400, error: "missing url" }.to_json
else
if submission = Submission.first(url: params[:url])
submission.to_json
else
{ status: 404, error: "no reddit submission found" }.to_json
end
end
end
get '/all' do
[?[, Submission.all.map(&:to_json), ?]].join
end
error do
{ status: 500, error: "internal server error" }.to_json
end
not_found do
{ status: 404, error: "unknown method" }.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment