Skip to content

Instantly share code, notes, and snippets.

@AlessandroMinali
Created October 26, 2016 15:32
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 AlessandroMinali/acc1ebfa885ba4b7aa876804da8b5931 to your computer and use it in GitHub Desktop.
Save AlessandroMinali/acc1ebfa885ba4b7aa876804da8b5931 to your computer and use it in GitHub Desktop.
The one true parallel universe.
# inspired by https://gist.github.com/techiferous/235068
require 'nokogiri'
module Rack
class Berenstein
def initialize(app, options = {})
@app = app
@options = options
end
def call(env)
@doc = nil
@request = Rack::Request.new(env)
status, @headers, @body = @app.call(env)
if html?
@body = doc.at_css("body").content
@body.gsub!(/berenstain/i, 'Berenstein')
update_content_length
end
[status, @headers, @body]
end
private
def html?
@headers["Content-Type"] && @headers["Content-Type"].include?("text/html")
end
def doc
@doc ||= Nokogiri::HTML(body_to_string)
end
def body_to_string
s = ""
@body.each { |x| s << x }
s
end
def update_content_length
@headers['Content-Length'] = Rack::Utils.bytesize(@body).to_s
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment