Module: Hesabu::MultiJSON

Defined in:
lib/hesabu/multi_json.rb

Overview

A wrapper to support both ‘oj` and normal `json`

‘oj` has some characteristics which make a very good candidate to be the preferred JSON parser for Hesabu. Mainly, it’s fast, and it stays fast for large payloads.

This module will check if ‘oj` is available and otherwise fall back to the regular JSON from the standard lib

Hesabu::MultiJSON::generate(object) # Generate JSON
Hesabu::MultiJSON::parse(string) # Parse JSON

Class Method Summary collapse

Class Method Details

.define_fast_json(receiver, name) ⇒ Object



58
59
60
61
62
63
# File 'lib/hesabu/multi_json.rb', line 58

def self.define_fast_json(receiver, name)
  cl = caller_locations(1..1).first
  method_body = public_send("#{name}_method")
  warn "Defining #{receiver}._fast_#{name} as #{method_body.inspect}"
  receiver.instance_eval method_body, cl.absolute_path, cl.lineno
end

.from_json_methodObject



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/hesabu/multi_json.rb', line 44

def self.from_json_method
  body = begin
           require "oj"
           %(::Oj.load(string, mode: :compat, time_format: :ruby, use_to_json: true))
         rescue LoadError
           %(JSON.parse(string, create_additions: false))
         end
  <<~METHOD
    def _fast_from_json(string)
      #{body}
    end
METHOD
end

.generate(object) ⇒ Object

Takes a ruby object and transforms it to JSON.



15
16
17
18
19
20
# File 'lib/hesabu/multi_json.rb', line 15

def self.generate(object)
  _fast_to_json(object)
rescue NameError
  define_fast_json(Hesabu::MultiJSON, "to_json")
  _fast_to_json(object)
end

.parse(string) ⇒ Object

Takes a string (hopefully containing JSON) and parses it to Ruby



23
24
25
26
27
28
# File 'lib/hesabu/multi_json.rb', line 23

def self.parse(string)
  _fast_from_json(string)
rescue NameError
  define_fast_json(Hesabu::MultiJSON, "from_json")
  _fast_from_json(string)
end

.to_json_methodObject



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/hesabu/multi_json.rb', line 30

def self.to_json_method
  body = begin
           require "oj"
           %(::Oj.dump(object, mode: :compat, time_format: :ruby, use_to_json: true))
         rescue LoadError
           %(JSON.fast_generate(object, create_additions: false, quirks_mode: true))
         end
  <<~METHOD
    def _fast_to_json(object)
      #{body}
    end
METHOD
end