Class: Zenaton::Services::Serializer
- Inherits:
-
Object
- Object
- Zenaton::Services::Serializer
- Defined in:
- lib/zenaton/services/serializer.rb
Overview
Encoding and decoding ruby objects into Zenaton’s json format
Constant Summary collapse
- ID_PREFIX =
this string prefixs ids that are used to identify objects
'@zenaton#'
- KEY_OBJECT =
JSON key for objects
'o'
- KEY_OBJECT_NAME =
JSON key for class name
'n'
- KEY_OBJECT_PROPERTIES =
JSON key for object ivars
'p'
- KEY_ARRAY =
JSON key for array and hashes
'a'
- KEY_DATA =
JSON key for json compatibles types
'd'
- KEY_STORE =
JSON key for deserialized complex object
's'
Instance Method Summary collapse
-
#decode(json_string) ⇒ Object
Decodes Zenaton’s format in a valid Ruby object.
-
#encode(data) ⇒ Object
Encodes a given ruby object to Zenaton’s json format.
-
#initialize ⇒ Serializer
constructor
A new instance of Serializer.
Constructor Details
#initialize ⇒ Serializer
Returns a new instance of Serializer.
21 22 23 |
# File 'lib/zenaton/services/serializer.rb', line 21 def initialize @properties = Properties.new end |
Instance Method Details
#decode(json_string) ⇒ Object
Decodes Zenaton’s format in a valid Ruby object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/zenaton/services/serializer.rb', line 43 def decode(json_string) parsed_json = JSON.parse(json_string) @decoded = [] @encoded = parsed_json.delete(KEY_STORE) case parsed_json.keys.first when KEY_DATA return parsed_json[KEY_DATA] when KEY_ARRAY return decode_enumerable(parsed_json[KEY_ARRAY]) when KEY_OBJECT id = parsed_json[KEY_OBJECT][ID_PREFIX.length..-1].to_i return decode_from_store(id, @encoded[id]) end end |
#encode(data) ⇒ Object
Encodes a given ruby object to Zenaton’s json format
28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/zenaton/services/serializer.rb', line 28 def encode(data) @encoded = [] @decoded = [] value = {} raise ArgumentError, 'Procs cannot be serialized' if data.is_a?(Proc) if basic_type?(data) value[KEY_DATA] = data else value[KEY_OBJECT] = encode_to_store(data) end value[KEY_STORE] = @encoded value.to_json end |