gotascii (owner)

Revisions

  • c57581 gotascii Sat Nov 07 08:01:50 -0800 2009
  • 23856f gotascii Fri Nov 06 13:23:33 -0800 2009
gist: 228298 Download_button fork
public
Description:
Pygments syntax highlighting via the unofficial pygments API http://pygments.appspot.com/
Public Clone URL: git://gist.github.com/228298.git
Embed All Files: show embed
pygrack.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
require 'net/http'
require 'uri'
require 'nokogiri'
 
class Pygrack
  def initialize(app)
    @app = app
  end
 
  def call(env)
    status, headers, response = @app.call(env)
 
    content = ''
    response.each{|str| content += str}
 
    doc = Nokogiri::HTML(content)
    nodes = doc.css("pre.code")
    nodes.each do |node|
      lang = node.attribute('class').value.gsub(/code (.*)/, '\1')
      code = node.content
      pygresp = Net::HTTP.post_form(URI.parse('http://pygments.appspot.com/'), {'lang' => lang, 'code' => code})
      nokopyg = Nokogiri::HTML(pygresp.body)
      pyg = nokopyg.css("div.highlight").first
      node.replace(pyg)
    end
 
    response = doc.to_s
    headers["Content-Length"] = response.length.to_s
    [status, headers, [response]]
  end
end