To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / .svn / pristine / 52 / 5207c75436c85ec591b380afe15450272eeedb94.svn-base @ 1297:0a574315af3e

History | View | Annotate | Download (2.32 KB)

1
module CodeRay
2
  
3
  # = Duo
4
  #
5
  # A Duo is a convenient way to use CodeRay. You just create a Duo,
6
  # giving it a lang (language of the input code) and a format (desired
7
  # output format), and call Duo#highlight with the code.
8
  # 
9
  # Duo makes it easy to re-use both scanner and encoder for a repetitive
10
  # task. It also provides a very easy interface syntax:
11
  # 
12
  #   require 'coderay'
13
  #   CodeRay::Duo[:python, :div].highlight 'import this'
14
  # 
15
  # Until you want to do uncommon things with CodeRay, I recommend to use
16
  # this method, since it takes care of everything.
17
  class Duo
18

    
19
    attr_accessor :lang, :format, :options
20
    
21
    # Create a new Duo, holding a lang and a format to highlight code.
22
    # 
23
    # simple:
24
    #   CodeRay::Duo[:ruby, :html].highlight 'bla 42'
25
    # 
26
    # with options:
27
    #   CodeRay::Duo[:ruby, :html, :hint => :debug].highlight '????::??'
28
    # 
29
    # alternative syntax without options:
30
    #   CodeRay::Duo[:ruby => :statistic].encode 'class << self; end'
31
    # 
32
    # alternative syntax with options:
33
    #   CodeRay::Duo[{ :ruby => :statistic }, :do => :something].encode 'abc'
34
    # 
35
    # The options are forwarded to scanner and encoder
36
    # (see CodeRay.get_scanner_options).
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
47
    
48
    class << self
49
      # To allow calls like Duo[:ruby, :html].highlight.
50
      alias [] new
51
    end
52
    
53
    # The scanner of the duo. Only created once.
54
    def scanner
55
      @scanner ||= CodeRay.scanner @lang, CodeRay.get_scanner_options(@options)
56
    end
57
    
58
    # The encoder of the duo. Only created once.
59
    def encoder
60
      @encoder ||= CodeRay.encoder @format, @options
61
    end
62
    
63
    # Tokenize and highlight the code using +scanner+ and +encoder+.
64
    def encode code, options = {}
65
      options = @options.merge options
66
      encoder.encode(code, @lang, options)
67
    end
68
    alias highlight encode
69
    
70
    # Allows to use Duo like a proc object:
71
    # 
72
    #  CodeRay::Duo[:python => :yaml].call(code)
73
    # 
74
    # or, in Ruby 1.9 and later:
75
    # 
76
    #  CodeRay::Duo[:python => :yaml].(code)
77
    alias call encode
78
    
79
  end
80
  
81
end