-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsmithy-json.rb
More file actions
86 lines (70 loc) · 1.89 KB
/
Copy pathsmithy-json.rb
File metadata and controls
86 lines (70 loc) · 1.89 KB
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
80
81
82
83
84
85
86
# frozen_string_literal: true
require 'smithy-schema'
require_relative 'smithy-json/builder'
require_relative 'smithy-json/codec'
require_relative 'smithy-json/parser'
module Smithy
# Smithy::Json is a purpose-built set of utilities for working with JSON.
module Json
VERSION = File.read(File.expand_path('../VERSION', __dir__.to_s)).strip
# Raised when a JSON parsing error occurs.
class ParseError < StandardError
def initialize(error)
@error = error
super(error.message)
end
attr_reader :error
end
# TODO: make this an instance
# def initialize(options = {})
# @engine = options[:engine] || self.class.engine
# end
class << self
# @param [Symbol, Class] engine
# Must be one of the following values:
#
# * :oj
# * :json
#
def engine=(engine)
@engine = engine.is_a?(Class) ? engine : load_engine(engine)
end
# @return [Class] Returns the default engine.
# One of:
#
# * {OjEngine}
# * {JsonEngine}
#
def engine
set_default_engine unless @engine
@engine
end
def load(json)
@engine.load(json)
end
def dump(value)
@engine.dump(value)
end
def set_default_engine
%i[oj json].each do |name|
@engine ||= try_load_engine(name)
end
return if @engine
raise 'Unable to find a compatible json library. ' \
'Ensure that you have installed or added to your Gemfile one of: oj or json'
end
private
def try_load_engine(name)
load_engine(name)
rescue LoadError
nil
end
def load_engine(name)
require "smithy-json/#{name}_engine"
const_name = "#{name[0].upcase}#{name[1..]}Engine"
const_get(const_name)
end
end
set_default_engine
end
end