summaryrefslogtreecommitdiff
path: root/lib/coderay/encoders/json.rb
blob: 7aa077c2876fe9729c5e99f394558b4126a2512b (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
($:.unshift '../..'; require 'coderay') unless defined? CodeRay
module CodeRay
module Encoders
  
  # = JSON Encoder
  class JSON < Encoder
    
    register_for :json
    FILE_EXTENSION = 'json'
    
  protected
    def setup options
      begin
        require 'json'
      rescue LoadError
        require 'rubygems'
        require 'json'
      end
      @out = []
    end
    
    def text_token text, kind
      { :type => 'text', :text => text, :kind => kind }
    end
    
    def block_token action, kind
      { :type => 'block', :action => action, :kind => kind }
    end
    
    def finish options
      @out.to_json
    end
    
  end
  
end
end

if $0 == __FILE__
  $VERBOSE = true
  $: << File.join(File.dirname(__FILE__), '..')
  eval DATA.read, nil, $0, __LINE__ + 4
end

__END__
require 'test/unit'
$:.delete '.'
require 'rubygems' if RUBY_VERSION < '1.9'

class JSONEncoderTest < Test::Unit::TestCase
  
  def test_json_output
    tokens = CodeRay.scan <<-RUBY, :ruby
puts "Hello world!"
    RUBY
    require 'json'
    assert_equal [
      {"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"},
      {"type"=>"text", "text"=>"\n", "kind"=>"space"}
    ], JSON.load(tokens.json)
  end
  
end