/
json.rb
69 lines (64 loc) · 1.5 KB
/
json.rb
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
begin
require 'multi_json'
rescue LoadError
require 'json'
end
module Hanami
module Utils
# JSON wrapper
#
# If you use MultiJson gem this wrapper will use it.
# Otherwise - JSON std lib.
#
# @since 0.8.0
module Json
# MultiJson adapter
#
# @since 0.9.1
# @api private
class MultiJsonAdapter
# @since 0.9.1
# @api private
def parse(payload)
MultiJson.load(payload)
end
# @since 0.9.1
# @api private
def generate(object)
MultiJson.dump(object)
end
end
# rubocop:disable Style/ClassVars
if defined?(MultiJson)
@@engine = MultiJsonAdapter.new
ParserError = MultiJson::ParseError
else
@@engine = ::JSON
ParserError = ::JSON::ParserError
end
# rubocop:enable Style/ClassVars
# Parse the given JSON paylod
#
# @param payload [String] a JSON payload
#
# @return [Object] the result of the loading process
#
# @raise [Hanami::Utils::Json::ParserError] if the paylod is invalid
#
# @since 0.9.1
def self.parse(payload)
@@engine.parse(payload)
end
# Generate a JSON document from the given object
#
# @param object [Object] any object
#
# @return [String] the result of the dumping process
#
# @since 0.9.1
def self.generate(object)
@@engine.generate(object)
end
end
end
end