Module: JSON::Minify

Included in:
JSON
Defined in:
lib/json/minify.rb,
lib/json/minify/version.rb

Constant Summary collapse

VERSION =
"0.0.2"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(mod) ⇒ Object



7
8
9
# File 'lib/json/minify.rb', line 7

def self.included(mod)
  mod.send(:extend, self)
end

Instance Method Details

#minify(str) ⇒ Object



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
# File 'lib/json/minify.rb', line 10

def minify(str)
  ss, buf = StringScanner.new(str), ''

  until ss.eos?
    # Remove whitespace
    if s = ss.scan(/\s+/)
      
    # Scan punctuation
    elsif s = ss.scan(/[{},:\]\[]/)
      buf << s

    # Scan strings
    elsif s = ss.scan(/""|(".*?[^\\])?"/)
      buf << s

    # Scan reserved words
    elsif s = ss.scan(/(true|false|null)/)
      buf << s

    # Scan numbers
    elsif s = ss.scan(/-?\d+([.]\d+)?([eE][-+]?[0-9]+)?/)
      buf << s

    # Remove C++ style comments
    elsif s = ss.scan(%r<//>)
      ss.scan_until(/(\r?\n|$)/)

    # Remove C style comments
    elsif s = ss.scan(%r'/[*]')
      ss.scan_until(%r'[*]/') or raise SyntaxError, "Unterminated /*...*/ comment - #{ss.rest}"

    # Anything else is invalid JSON
    else
      raise SyntaxError, "Unable to pre-scan string: #{ss.rest}"
    end
  end
  buf
end

#minify_parse(buf) ⇒ Object



49
50
51
# File 'lib/json/minify.rb', line 49

def minify_parse(buf)
  JSON.parse(minify(buf))
end