To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.
root / .svn / pristine / 49 / 49c759950bed453cc0da75c2904a201b6bf1a7c4.svn-base @ 1297:0a574315af3e
History | View | Annotate | Download (1.79 KB)
| 1 |
module CodeRay |
|---|---|
| 2 |
module Encoders |
| 3 |
|
| 4 |
# A simple JSON Encoder. |
| 5 |
# |
| 6 |
# Example: |
| 7 |
# CodeRay.scan('puts "Hello world!"', :ruby).json
|
| 8 |
# yields |
| 9 |
# [ |
| 10 |
# {"type"=>"text", "text"=>"puts", "kind"=>"ident"},
|
| 11 |
# {"type"=>"text", "text"=>" ", "kind"=>"space"},
|
| 12 |
# {"type"=>"block", "action"=>"open", "kind"=>"string"},
|
| 13 |
# {"type"=>"text", "text"=>"\"", "kind"=>"delimiter"},
|
| 14 |
# {"type"=>"text", "text"=>"Hello world!", "kind"=>"content"},
|
| 15 |
# {"type"=>"text", "text"=>"\"", "kind"=>"delimiter"},
|
| 16 |
# {"type"=>"block", "action"=>"close", "kind"=>"string"},
|
| 17 |
# ] |
| 18 |
class JSON < Encoder |
| 19 |
|
| 20 |
begin |
| 21 |
require 'json' |
| 22 |
rescue LoadError |
| 23 |
begin |
| 24 |
require 'rubygems' unless defined? Gem |
| 25 |
gem 'json' |
| 26 |
require 'json' |
| 27 |
rescue LoadError |
| 28 |
$stderr.puts "The JSON encoder needs the JSON library.\n" \ |
| 29 |
"Please gem install json." |
| 30 |
raise |
| 31 |
end |
| 32 |
end |
| 33 |
|
| 34 |
register_for :json |
| 35 |
FILE_EXTENSION = 'json' |
| 36 |
|
| 37 |
protected |
| 38 |
def setup options |
| 39 |
super |
| 40 |
|
| 41 |
@first = true |
| 42 |
@out << '[' |
| 43 |
end |
| 44 |
|
| 45 |
def finish options |
| 46 |
@out << ']' |
| 47 |
end |
| 48 |
|
| 49 |
def append data |
| 50 |
if @first |
| 51 |
@first = false |
| 52 |
else |
| 53 |
@out << ',' |
| 54 |
end |
| 55 |
|
| 56 |
@out << data.to_json |
| 57 |
end |
| 58 |
|
| 59 |
public |
| 60 |
def text_token text, kind |
| 61 |
append :type => 'text', :text => text, :kind => kind |
| 62 |
end |
| 63 |
|
| 64 |
def begin_group kind |
| 65 |
append :type => 'block', :action => 'open', :kind => kind |
| 66 |
end |
| 67 |
|
| 68 |
def end_group kind |
| 69 |
append :type => 'block', :action => 'close', :kind => kind |
| 70 |
end |
| 71 |
|
| 72 |
def begin_line kind |
| 73 |
append :type => 'block', :action => 'begin_line', :kind => kind |
| 74 |
end |
| 75 |
|
| 76 |
def end_line kind |
| 77 |
append :type => 'block', :action => 'end_line', :kind => kind |
| 78 |
end |
| 79 |
|
| 80 |
end |
| 81 |
|
| 82 |
end |
| 83 |
end |