Module: Familia::JsonSerializer

Defined in:
lib/familia/json_serializer.rb

Overview

JsonSerializer provides a high-performance JSON interface using OJ

This module wraps OJ with a clean API that can be easily swapped out or benchmarked against other JSON implementations. Uses OJ's :strict mode for RFC 7159 compliant JSON output.

Examples:

Basic usage

data = { name: 'test', value: 123 }
json = Familia::JsonSerializer.dump(data)
parsed = Familia::JsonSerializer.parse(json, symbolize_names: true)

Class Method Summary collapse

Class Method Details

.dump(obj) ⇒ String

Serialize Ruby object to JSON string

Parameters:

  • obj (Object)

    Ruby object to serialize

Returns:

  • (String)

    JSON string



42
43
44
45
46
# File 'lib/familia/json_serializer.rb', line 42

def dump(obj)
  Oj.dump(obj, mode: :strict)
rescue Oj::Error, TypeError, EncodingError => e
  raise SerializerError, e.message
end

.generate(obj) ⇒ String

Alias for dump for JSON gem compatibility

Parameters:

  • obj (Object)

    Ruby object to serialize

Returns:

  • (String)

    JSON string



52
53
54
55
56
# File 'lib/familia/json_serializer.rb', line 52

def generate(obj)
  Oj.dump(obj, mode: :strict)
rescue Oj::Error, TypeError, EncodingError => e
  raise SerializerError, e.message
end

.parse(source, opts = {}) ⇒ Object

Parse JSON string into Ruby objects

Parameters:

  • source (String)

    JSON string to parse

  • opts (Hash) (defaults to: {})

    parsing options

Options Hash (opts):

  • :symbolize_names (Boolean)

    convert hash keys to symbols

Returns:

  • (Object)

    parsed Ruby object

Raises:



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/familia/json_serializer.rb', line 24

def parse(source, opts = {})
  return nil if source.nil? || source == ''

  symbolize_names = opts[:symbolize_names] || opts['symbolize_names']

  if symbolize_names
    Oj.load(source, mode: :strict, symbol_keys: true)
  else
    Oj.load(source, mode: :strict)
  end
rescue Oj::ParseError, Oj::Error, EncodingError => e
  raise SerializerError, e.message
end

.pretty_generate(obj) ⇒ String

Serialize Ruby object to pretty-formatted JSON string

Parameters:

  • obj (Object)

    Ruby object to serialize

Returns:

  • (String)

    pretty-formatted JSON string



62
63
64
65
66
# File 'lib/familia/json_serializer.rb', line 62

def pretty_generate(obj)
  Oj.dump(obj, mode: :strict, indent: 2)
rescue Oj::Error, TypeError, EncodingError => e
  raise SerializerError, e.message
end