Class ServerSide::JS
In: lib/serverside/js.rb
Parent: Object

Serializes data into a Javscript literal hash format. For example: ServerSide::JS.new {|j| j}

Methods

Constants

NULL = 'null'.freeze

Public Class methods

Initializes a new document. A callback function name can be supplied to wrap the hash.

[Source]

    # File lib/serverside/js.rb, line 15
15:     def initialize(callback = nil, &block)
16:       @callback = callback
17:       @stack = [self]
18:       block.call(self) if block
19:     end

Public Instance methods

[Source]

    # File lib/serverside/js.rb, line 46
46:     def <<(value)
47:       value = value.__content if value.respond_to?(:__content)
48:       @stack.last.__add_array_value(value)
49:     end

[Source]

    # File lib/serverside/js.rb, line 41
41:     def __add_array_value(value)
42:       @content ||= []
43:       @content << value
44:     end

[Source]

    # File lib/serverside/js.rb, line 36
36:     def __add_hash_value(key, value)
37:       @content ||= {}
38:       @content[key] = value
39:     end

Returns the current document content.

[Source]

    # File lib/serverside/js.rb, line 52
52:     def __content
53:       @content
54:     end

Serializes the specified object into JS/JSON format.

[Source]

    # File lib/serverside/js.rb, line 59
59:     def __serialize(obj)
60:       case obj
61:       when Time: JSON.generate(obj.to_f)
62:       else
63:         JSON.generate(obj)
64:       end
65:     end
inspect()

Alias for to_s

Catches calls to define keys and creates methods on the fly.

[Source]

    # File lib/serverside/js.rb, line 22
22:     def method_missing(key, *args, &block)
23:       value = nil
24:       if block
25:         @stack.push JS.new
26:         block.call(self)
27:         value = @stack.pop.__content
28:       else
29:         value = args.first
30:         value = value.__content if value.respond_to?(:__content)
31:       end
32:       @stack.last.__add_hash_value(key, value)
33:       self
34:     end
to_json()

Alias for to_s

Returns the document content as a literal Javascript object. If a callback was specified, the object is wrapped in a Javascript function call.

[Source]

    # File lib/serverside/js.rb, line 69
69:     def to_s
70:       j = __serialize(@content)
71:       @callback ? "#{@callback}(#{j});" : j
72:     end

[Validate]