Module: TextTube::Baby::Coderay

Extended by:
Filterable
Defined in:
lib/texttube/baby/coderay.rb

Overview

Note:

Thanks to Rob Emerson for sharing his nanoc filter which helped me write this.

a filter for Coderay

Class Method Summary collapse

Class Method Details

.codify(str, lang) ⇒ Object

Run the Coderay scanner.

Examples:

self.class.codify "x = 2", "ruby"

Parameters:



72
73
74
# File 'lib/texttube/baby/coderay.rb', line 72

def self.codify(str, lang)
	::CodeRay.scan(str, lang).html
end

.html_unescape(a_string) ⇒ Object

Unescape the HTML as the Coderay scanner won’t work otherwise.



61
62
63
64
# File 'lib/texttube/baby/coderay.rb', line 61

def self.html_unescape(a_string)
	a_string.gsub('&amp;', '&').gsub('&lt;', '<').gsub('&gt;', 
	'>').gsub('&quot;', '"')
end

.run(content, options = {}) ⇒ String

Parameters:

  • content (String)
  • options (Hash) (defaults to: {})

Returns:



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
56
57
# File 'lib/texttube/baby/coderay.rb', line 25

def self.run(content, options={})
	options = {lang: :ruby } if options.blank?
	doc = Oga.parse_html content

	if (xpath = doc.xpath("pre/code"))
	  xpath.map do |codeblock|
         #un-escape as Coderay will escape it again
         inner_html = codeblock.inner_text

         # following the convention of Rack::Codehighlighter
         if inner_html.start_with?("::::")
           lines = inner_html.split("\n")
           options[:lang] = lines.shift.match(%r{::::(\w+)})[1].to_sym
           inner_html = lines.join("\n")
         end

         if (options[:lang] == :skip) || (! options.has_key? :lang )
           codeblock.inner_text = inner_html
         else
         # html_unescape(inner_html)
         #  code = codify(html_unescape(inner_html), options[:lang])
           code = Coderay.codify(Coderay.html_unescape(inner_html), options[:lang])
           # It needs to be parsed back into Oga
           # or the escaping goes wrong
           codeblock.children= Oga.parse_html( code ).children
           codeblock.set "class", "CodeRay"
         end
       end#block
       doc.to_xml
     else
       content
     end
end