8784: Fix test for latest firefox.
[arvados.git] / services / api / lib / serializers.rb
1 require 'safe_json'
2
3 class Serializer
4   class TypeMismatch < ArgumentError
5   end
6
7   def self.dump(val)
8     if !val.is_a?(object_class)
9       raise TypeMismatch.new("cannot serialize #{val.class} as #{object_class}")
10     end
11     SafeJSON.dump(val)
12   end
13
14   def self.legacy_load(s)
15     val = Psych.safe_load(s)
16     if val.is_a? String
17       # If apiserver was downgraded to a YAML-only version after
18       # storing JSON in the database, the old code would have loaded
19       # the JSON document as a plain string, and then YAML-encoded
20       # it when saving it back to the database. It's too late now to
21       # make the old code behave better, but at least we can
22       # gracefully handle the mess it leaves in the database by
23       # double-decoding on the way out.
24       return SafeJSON.load(val)
25     else
26       return val
27     end
28   end
29
30   def self.load(s)
31     if s.nil?
32       object_class.new()
33     elsif s[0] == first_json_char
34       SafeJSON.load(s)
35     elsif s[0..2] == "---"
36       legacy_load(s)
37     else
38       raise "invalid serialized data #{s[0..5].inspect}"
39     end
40   end
41 end
42
43 class HashSerializer < Serializer
44   def self.first_json_char
45     "{"
46   end
47
48   def self.object_class
49     ::Hash
50   end
51 end
52
53 class ArraySerializer < Serializer
54   def self.first_json_char
55     "["
56   end
57
58   def self.object_class
59     ::Array
60   end
61 end