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

call   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, :html].highlight 'bla 42'

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 37
37:     def initialize lang = nil, format = nil, options = {}
38:       if format.nil? && lang.is_a?(Hash) && lang.size == 1
39:         @lang = lang.keys.first
40:         @format = lang[@lang]
41:       else
42:         @lang = lang
43:         @format = format
44:       end
45:       @options = options
46:     end

Public Instance methods

call(code, options = {})

Alias for encode

Tokenize and highlight the code using scanner and encoder.

[Source]

    # File lib/coderay/duo.rb, line 64
64:     def encode code, options = {}
65:       options = @options.merge options
66:       encoder.encode(code, @lang, options)
67:     end

The encoder of the duo. Only created once.

[Source]

    # File lib/coderay/duo.rb, line 59
59:     def encoder
60:       @encoder ||= CodeRay.encoder @format, @options
61:     end
highlight(code, options = {})

Alias for encode

The scanner of the duo. Only created once.

[Source]

    # File lib/coderay/duo.rb, line 54
54:     def scanner
55:       @scanner ||= CodeRay.scanner @lang, CodeRay.get_scanner_options(@options)
56:     end

[Validate]