-
Notifications
You must be signed in to change notification settings - Fork 51
/
serialize.module.coffee
79 lines (63 loc) · 1.87 KB
/
serialize.module.coffee
1
2
3
4
5
6
7
8
9
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# This class serializes objects into a JSON string,
# and then can de-serialize JSON strings into instances.
#
# Serialized objects are in the following format:
# {id: 'path/to/module.Exports', value: objectValue}
#
# You should override the object's value:
# toValue: -> @properties
#
# The objects value will be passed to it's constructor
# function upon instantiation.
fromObject = (object) ->
return object unless object?
# If type is native, return
unless typeof object is 'object'
return object
# If type is array, call recursively
if Array.isArray(object)
return (fromObject(o) for o in object)
# If type is object, and we're not dealing
# with a instance, resolve recursively
unless object.id
for k, v of object
object[k] = fromObject(v)
return object
# Otherwise, we're dealing with an instance.
# Find the instance by ID, and then instantiate
# it, passing object.value
[path, name] = object.id.split('.', 2)
constructor = require(path)
constructor = constructor[name] if name
# Constructor supports a custom fromValue function
if result = constructor.fromValue?(object)
return result
# Recursively find objects
args = fromObject(object.value)
if Array.isArray(args)
# Constructor functions can't
# use apply() or call(), so we have
# to manually pass arguments.
new constructor(
args[0], args[1], args[2],
args[3], args[4], args[5]
)
else
new constructor(args)
fromJSON = (object) ->
if typeof object is 'string'
object = JSON.parse(object)
fromObject(object)
Serialize =
# ID Needs to be overridden in each
# class Serialize is included in
id: ->
module.id
toJSON: ->
result =
id: @id?() or @id
value: @toValue?() or @toValue
clone: ->
fromJSON(JSON.stringify(this))
module.exports.Serialize = Serialize
module.exports.fromJSON = fromJSON