summaryrefslogtreecommitdiff
path: root/lib/coderay/encoders/json.rb
blob: 9da3238ae5627adec9908e94f6ba13d7b5eac2c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
module CodeRay
module Encoders
  
  # A simple JSON Encoder.
  # 
  # Example:
  #  CodeRay.scan('puts "Hello world!"', :ruby).json
  # yields
  #  [
  #    {"type"=>"text", "text"=>"puts", "kind"=>"ident"},
  #    {"type"=>"text", "text"=>" ", "kind"=>"space"},
  #    {"type"=>"block", "action"=>"open", "kind"=>"string"},
  #    {"type"=>"text", "text"=>"\"", "kind"=>"delimiter"},
  #    {"type"=>"text", "text"=>"Hello world!", "kind"=>"content"},
  #    {"type"=>"text", "text"=>"\"", "kind"=>"delimiter"},
  #    {"type"=>"block", "action"=>"close", "kind"=>"string"},
  #  ]
  class JSON < Encoder
    
    begin
      require 'json'
    rescue LoadError
      begin
        require 'rubygems'
        gem "json#{'-jruby' if defined? JRUBY_VERSION}"
        require 'json'
      rescue LoadError
        $stderr.puts "The JSON encoder needs the JSON library.\n" \
          "Please gem install json."
        raise
      end
    end
    
    register_for :json
    FILE_EXTENSION = 'json'
    
  protected
    def setup options
      @out = []
    end
    
    def finish options
      @out.to_json
    end
    
  public
    def text_token text, kind
      @out << { :type => 'text', :text => text, :kind => kind }
    end
    
    def begin_group kind
      @out << { :type => 'block', :action => 'open', :kind => kind }
    end
    
    def end_group kind
      @out << { :type => 'block', :action => 'close', :kind => kind }
    end
    
    def begin_line kind
      @out << { :type => 'block', :action => 'begin_line', :kind => kind }
    end
    
    def end_line kind
      @out << { :type => 'block', :action => 'end_line', :kind => kind }
    end
    
  end
  
end
end