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



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

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

.parse(string) ⇒ Object

Parses JSON string



40
41
42
# File 'lib/jsduck/json_duck.rb', line 40

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

.pretty=(pretty) ⇒ Object

Set to true to turn on pretty-formatting of JSON



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

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

.read(filename) ⇒ Object

Reads and parses JSON from file



35
36
37
# File 'lib/jsduck/json_duck.rb', line 35

def self.read(filename)
  self.parse(IO.read(filename))
end

.write_json(filename, data) ⇒ Object

Turns object into JSON and writes inside a file



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

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.



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

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