Module: BEL::JSON

Defined in:
lib/bel/json.rb,
lib/bel/json/reader.rb,
lib/bel/json/writer.rb,
lib/bel/json/adapter/oj.rb,
lib/bel/json/adapter/ruby_json.rb,
lib/bel/json/adapter/multi_json.rb

Overview

TODO Document.

What does this abstraction provide? Why is it here?

Defined Under Namespace

Modules: Reader, Writer Classes: Implementation, StreamHandler

Class Method Summary collapse

Class Method Details

.adapterObject

Load the most suitable JSON implementation available within ruby. The load order attempted is:

  • oj (provides stream parsing utilizing event callbacks)

  • multi_json (simple buffering abstraction over multiple ruby libraries)

  • json (stock ruby implementation)



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
# File 'lib/bel/json.rb', line 38

def self.adapter
  implementations = [
    'json/adapter/oj',
    'json/adapter/multi_json',
    'json/adapter/ruby_json'
  ]

  load_success = implementations.any? { |impl|
    begin
      require_relative impl
      true
    rescue LoadError
      # Could not load +impl_module+; try the next one
      false
    end
  }

  if load_success
    BEL::JSON::Implementation
  else
    mod_s = impl_modules.join(', ')
    msg   = "Could not load any JSON implementation (tried: #{mod_s})."
    raise LoadError.new(msg)
  end
end

.read(data, options = {}) ⇒ Object

TODO Document.

Reads JSON data. Leverages JSON adapters which implement the same signature.



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/bel/json.rb', line 11

def self.read(data, options = {})
  @adapter ||= self.adapter
  instance = @adapter.new

  if block_given?
    instance.read(data, options) { |obj|
      yield obj
    }
  else
    instance.read(data, options)
  end
end

.write(data, output_io, options = {}) ⇒ Object

TODO Document.

Writes JSON data. Leverages JSON adapters which implement the same signature.



27
28
29
30
31
# File 'lib/bel/json.rb', line 27

def self.write(data, output_io, options = {})
  @adapter ||= self.adapter
  instance = @adapter.new
  instance.write(data, output_io, options)
end