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



44
45
46
47
48
# File 'lib/familia/json_serializer.rb', line 44

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



54
55
56
57
58
# File 'lib/familia/json_serializer.rb', line 54

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:



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

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



64
65
66
67
68
# File 'lib/familia/json_serializer.rb', line 64

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