Created
April 18, 2011 23:01
-
-
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'
This file contains hidden or 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 '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" /> |
This file contains hidden or 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 'app' | |
| require 'malcom_in_the_middleware' | |
| use Malcom | |
| run App |
This file contains hidden or 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
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
rackup config.ru