Class CodeRay::Duo
In: lib/coderay/duo.rb
Parent: Object

Duo

A Duo is a convenient way to use CodeRay. You just create a Duo, giving it a lang (language of the input code) and a format (desired output format), and call Duo#highlight with the code.

Duo makes it easy to re-use both scanner and encoder for a repetitive task. It also provides a very easy interface syntax:

  require 'coderay'
  CodeRay::Duo[:python, :div].highlight 'import this'

Until you want to do uncommon things with CodeRay, I recommend to use this method, since it takes care of everything.

Methods

encode   encoder   highlight   new   scanner  

External Aliases

new -> []
  To allow calls like Duo[:ruby, :html].highlight.

Attributes

format  [RW] 
lang  [RW] 
options  [RW] 

Public Class methods

Create a new Duo, holding a lang and a format to highlight code.

simple:

  CodeRay::Duo[:ruby, :page].highlight 'bla 42'

streaming:

  CodeRay::Duo[:ruby, :page].highlight 'bar 23', :stream => true

with options:

  CodeRay::Duo[:ruby, :html, :hint => :debug].highlight '????::??'

alternative syntax without options:

  CodeRay::Duo[:ruby => :statistic].encode 'class << self; end'

alternative syntax with options:

  CodeRay::Duo[{ :ruby => :statistic }, :do => :something].encode 'abc'

The options are forwarded to scanner and encoder (see CodeRay.get_scanner_options).

[Source]

    # File lib/coderay/duo.rb, line 40
40:     def initialize lang = nil, format = nil, options = {}
41:       if format == nil and lang.is_a? Hash and lang.size == 1
42:         @lang = lang.keys.first
43:         @format = lang[@lang]
44:       else
45:         @lang = lang
46:         @format = format
47:       end
48:       @options = options
49:     end

Public Instance methods

Tokenize and highlight the code using scanner and encoder.

If the :stream option is set, the Duo will go into streaming mode, saving memory for the cost of time.

[Source]

    # File lib/coderay/duo.rb, line 70
70:     def encode code, options = { :stream => false }
71:       stream = options.delete :stream
72:       options = @options.merge options
73:       if stream
74:         encoder.encode_stream(code, @lang, options)
75:       else
76:         scanner.code = code
77:         encoder.encode_tokens(scanner.tokenize, options)
78:       end
79:     end

The encoder of the duo. Only created once.

[Source]

    # File lib/coderay/duo.rb, line 62
62:     def encoder
63:       @encoder ||= CodeRay.encoder @format, @options
64:     end
highlight(code, options = { :stream => false })

Alias for encode

The scanner of the duo. Only created once.

[Source]

    # File lib/coderay/duo.rb, line 57
57:     def scanner
58:       @scanner ||= CodeRay.scanner @lang, CodeRay.get_scanner_options(@options)
59:     end

[Validate]