Class: JsDuck::JsonDuck

Inherits:
Object
  • Object
show all
Defined in:
lib/jsduck/json_duck.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).

Constant Summary collapse

@@pretty =
false

Class Method Summary collapse

Class Method Details

.generate(data) ⇒ Object

Generates JSON from object



31
32
33
# File 'lib/jsduck/json_duck.rb', line 31

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

.parse(string) ⇒ Object

Parses JSON string



46
47
48
# File 'lib/jsduck/json_duck.rb', line 46

def self.parse(string)
  JSON.parse(string)
end

.pretty=(pretty) ⇒ Object

Set to true to turn on pretty-formatting of JSON



14
15
16
# File 'lib/jsduck/json_duck.rb', line 14

def self.pretty=(pretty)
  @@pretty = pretty
end

.read(filename) ⇒ Object

Reads and parses JSON from file



36
37
38
39
40
41
42
43
# File 'lib/jsduck/json_duck.rb', line 36

def self.read(filename)
  begin
    self.parse(JsDuck::IO.read(filename))
  rescue
    puts "Oh noes!  #{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



26
27
28
# File 'lib/jsduck/json_duck.rb', line 26

def self.write_json(filename, data)
  File.open(filename, 'w') {|f| f.write(self.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.



20
21
22
23
# File 'lib/jsduck/json_duck.rb', line 20

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