Class: Rack::Pygments

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

Defined Under Namespace

Modules: Version

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
# File 'lib/rack/pygments.rb', line 17

def call(env)
  status, headers, response = @app.call(env)
  return [status, headers, response] unless pygmentize?(status, headers)
  response_body = pygmentize(response.join)
  headers["Content-Length"] = response_body.length.to_s
  [status,headers,[response_body]]
end

#pygmentize(content) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rack/pygments.rb', line 29

def pygmentize(content)
  document = Nokogiri::HTML(content)
  nodes = document.css(@tag)
  nodes.each do |node|
    lang = node.attribute(@attr).nil? ? 'bash' : node.attribute(@attr).value

    file = Tempfile.new('pygments')
    file.write node.content
    file.close

    pygmentized = `#{@bin} -l #{lang} -f html #{file.path}`

    file.delete

    node.replace(Nokogiri::HTML(pygmentized).css("div.highlight").first)
  end
  document.to_s
end

#pygmentize?(status, headers) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/rack/pygments.rb', line 25

def pygmentize?(status, headers)
  status == 200 && headers['Content-Type'] =~ /html/
end