Skip to content

Instantly share code, notes, and snippets.

@coderoshi
Created May 24, 2012 16:55
Show Gist options
  • Save coderoshi/2782755 to your computer and use it in GitHub Desktop.
Save coderoshi/2782755 to your computer and use it in GitHub Desktop.
A Sinatra example to turn any site into a JSON service
require 'rubygems'
require 'sinatra'
require 'httparty'
require 'nokogiri'
require 'json'
class HtmlParserIncluded < HTTParty::Parser
SupportedFormats.merge!('text/html' => :html)
def html
Nokogiri::HTML(body)
end
end
class Page
include HTTParty
parser HtmlParserIncluded
end
get '/' do
"Here there be cat$"
end
get '/bomb' do
content_type :json
count = params[:count].to_i
count = 5 if count < 1
page = ((rand * 24) + 1).to_i
res = Page.get("http://cashcats.biz/page/#{page}")
cats = res.css('.photo_img').map{|x| x['src']}
cats = cats.sort_by{ rand }[0...count]
{ cats: cats }.to_json
end
# Just deploy these files to Heroku
require './app'
run Sinatra::Application
source :rubygems
gem 'sinatra'
gem 'httparty'
gem 'nokogiri'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment