Class: Rack::Pygments

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/pygments.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ Pygments

Returns a new instance of Pygments.



6
7
8
9
10
11
12
13
14
15
# File 'lib/rack/pygments.rb', line 6

def initialize(app, opts={})
  @app = app
  @tag = opts[:html_tag].nil? ? 'highlight' : opts[:html_tag] 
  @attr = opts[:html_attr].nil? ? 'lang' : opts[:html_attr]
  if system("which pygmentize > /dev/null")
    @bin = `which pygmentize`.chomp
  else
    raise Exception, "Pygmentize is missing"
  end
end

Instance Method Details

#call(env) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/rack/pygments.rb', line 17

def call(env)
  if env["PATH_INFO"] !~ /.*\.css$/
  status, headers, response = @app.call(env)
  content = response.instance_variable_get("@body").to_s
    document = Nokogiri::HTML(content)
    nodes = document.css(@tag)
    nodes.each do |node|
      lang = node.attribute(@attr).nil? ? 'bash' : node.attribute(@attr).value
      pygmentize = `echo '#{node.content}' | #{@bin} -l #{lang} -f html`
      node.replace(Nokogiri::HTML(pygmentize).css("div.highlight").first)
    end
    response = document.to_s
    headers["Content-Length"] = response.length.to_s
    [status,headers,[response]]
  else
    @app.call(env)
  end
end