Skip to content

Instantly share code, notes, and snippets.

@jamesmartin
Created April 18, 2011 23:01
Show Gist options
  • Save jamesmartin/926460 to your computer and use it in GitHub Desktop.
Save jamesmartin/926460 to your computer and use it in GitHub Desktop.
Middleware that rewrites every image to be 'The Best Image on the Internet'
require 'rubygems'
require 'sinatra'
Sinatra::Base.inline_templates = true
class App < Sinatra::Base
get '/' do
erb :index
end
end
__END__
@@ index
<h1>Hello, World</h1>
<img src="/T3Zox.jpg" width="100" height="100" />
require 'app'
require 'malcom_in_the_middleware'
use Malcom
run App
class Malcom
require 'nokogiri'
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
static_dir = "http://thebestpictureontheinternet.com/"
body = Nokogiri::HTML(body.first)
body.css('img').each do |image|
original = image.attributes.fetch('src').value
original.gsub!(/^\//, '')
image.attributes.fetch('src').value = "#{static_dir}#{original}"
end
headers['Content-Length'] = body.to_html.length.to_s
[status, headers, body.to_html]
end
end
@jamesmartin
Copy link
Author

rackup config.ru

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment