Class: JsDuck::Util::Json

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/jsduck/util/json.rb

Overview

Wrapper around the json gem for use in JsDuck.

The main benefit of it is that we have a central place for controlling how the JSON is created (pretty-formatted or not).

Instance Method Summary collapse

Methods included from Singleton

included

Constructor Details

#initializeJson

Returns a new instance of Json.



16
17
18
# File 'lib/jsduck/util/json.rb', line 16

def initialize
  @pretty = false
end

Instance Method Details

#generate(data) ⇒ Object

Generates JSON from object



38
39
40
# File 'lib/jsduck/util/json.rb', line 38

def generate(data)
  @pretty ? JSON.pretty_generate(data) : JSON.generate(data)
end

#parse(string, opts = {}) ⇒ Object

Parses JSON string



53
54
55
# File 'lib/jsduck/util/json.rb', line 53

def parse(string, opts = {})
  JSON.parse(string, opts)
end

#pretty=(pretty) ⇒ Object

Set to true to turn on pretty-formatting of JSON



21
22
23
# File 'lib/jsduck/util/json.rb', line 21

def pretty=(pretty)
  @pretty = pretty
end

#read(filename) ⇒ Object

Reads and parses JSON from file



43
44
45
46
47
48
49
50
# File 'lib/jsduck/util/json.rb', line 43

def read(filename)
  begin
    parse(Util::IO.read(filename))
  rescue
    Logger.fatal("#{filename} is not a valid JSON file")
    exit(1)
  end
end

#write_json(filename, data) ⇒ Object

Turns object into JSON and writes inside a file



33
34
35
# File 'lib/jsduck/util/json.rb', line 33

def write_json(filename, data)
  File.open(filename, 'w') {|f| f.write(generate(data)) }
end

#write_jsonp(filename, callback_name, data) ⇒ Object

Turns object into JSON, places it inside JavaScript that calls the given callback name, and writes the result to file.



27
28
29
30
# File 'lib/jsduck/util/json.rb', line 27

def write_jsonp(filename, callback_name, data)
  jsonp = "Ext.data.JsonP." + callback_name + "(" + generate(data) + ");"
  File.open(filename, 'w') {|f| f.write(jsonp) }
end