Skip to content

Instantly share code, notes, and snippets.

@MrDys
Created September 12, 2012 16:47
Show Gist options
  • Save MrDys/3708030 to your computer and use it in GitHub Desktop.
Save MrDys/3708030 to your computer and use it in GitHub Desktop.
Rack middleware to add in nice typographic features
This quick little middleware grabs all HTML pages going across the wire, peeks inside and replaces the content with some nice features: curly quotes instead of straight quotes (prime marks), conversion of -- to proper emdashes, insertion of   to prevent text widows, wrapper HTML classes for caps and ampersands for fancier styling, and other fun things.
It's really a middleware wrapper for Typogruby (http://avdgaag.github.com/typogruby/), so check it out if you want the gory details.
It requires:
typogruby: http://avdgaag.github.com/typogruby/
nokogiri: http://nokogiri.org/
Have fun!
require 'typogruby'
require 'nokogiri'
module Rack
class Typo
def initialize(app)
@app = app
end
def call(env)
status, headers, response = @app.call(env)
if headers["Content-Type"].include? "text/html"
s = ""
response.body.each { |x| s << x}
doc = Nokogiri::HTML(s)
doc.encoding = 'UTF-8'
doc.at_css("body").traverse do |node|
if node.text?
node.replace(Nokogiri::HTML.fragment(Typogruby.improve(node.content)))
end
end
response.body = doc.to_html.lines.to_a
end
[status, headers, response]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment