Class: Rack::Codehighlighter

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/rack/codehighlighter.rb

Constant Summary collapse

FORMAT =

for logging use

%{%s - [%s] [%s] "%s %s%s %s" (%s) %d %d %0.4f\n}

Instance Method Summary collapse

Constructor Details

#initialize(app, highlighter = :censor, opts = {}) ⇒ Codehighlighter

Returns a new instance of Codehighlighter.



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rack/codehighlighter.rb', line 11

def initialize(app, highlighter = :censor, opts = {})
  @app = app
  @highlighter = highlighter
  @opts = {
    :element => "pre",
    :pattern => /\A:::([-\w]+)\s*(\n|
)/i,  # 
 == line feed
    :reason => "[[--  ugly code removed  --]]", #8-)
    :markdown => false
  }
  @opts.merge! opts
end

Instance Method Details

#call(env) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rack/codehighlighter.rb', line 23

def call(env)
  began_at = Time.now
  status, headers, response = @app.call(env)
  headers = HeaderHash.new(headers)

  if !STATUS_WITH_NO_ENTITY_BODY.include?(status) &&
     !headers['transfer-encoding'] &&
      headers['content-type'] &&
      headers['content-type'].include?("text/html")

    content = ""
    response.each { |part| content += part }
    doc = Nokogiri::HTML(content, nil, 'UTF-8')
    nodes = doc.search(@opts[:element])
    nodes.each do |node|
      s = node.inner_html || "[++where is the code?++]"
      if @opts[:markdown]
        node.parent.swap(send(@highlighter, s))
      else
        node.swap(send(@highlighter, s))
      end
    end

    body = doc.to_html

    headers['Content-Length'] = body.bytesize.to_s

    log(env, status, headers, began_at) if @opts[:logging]
    [status, headers, [body]]
  else
    [status, headers, response]
  end
end