Module: Familia::Refinements::DearJsonHashMethods

Defined in:
lib/familia/refinements/dear_json.rb

Overview

DearJson provides standard JSON methods for core Ruby classes using Familia's secure JsonSerializer (OJ in strict mode).

This refinement allows developers to use the standard Ruby JSON interface (as_json, to_json) on Hash and Array objects while ensuring all JSON serialization goes through Familia's controlled, secure serialization.

Security Benefits:

  • All JSON serialization uses OJ strict mode
  • Prevents accidental exposure of sensitive objects
  • Maintains Familia's security-first approach
  • Provides familiar Ruby JSON interface

Examples:

Basic usage with refinement

using Familia::Refinements::DearJson

data = { user: user.as_json, tags: user.tags.as_json }
json = data.to_json  # Uses Familia::JsonSerializer.dump

mixed_array = [user, user.tags, { meta: 'info' }]
json = mixed_array.to_json  # Handles mixed Familia/core objects

Without refinement (manual approach)

data = { user: user.as_json, tags: user.tags.as_json }
json = Familia::JsonSerializer.dump(data)

Instance Method Summary collapse

Instance Method Details

#as_json(options = nil) ⇒ Hash

Convert hash to JSON-serializable representation. This method recursively calls as_json on nested values to ensure Familia objects are properly serialized in nested structures.

Parameters:

  • options (Hash) (defaults to: nil)

    Optional parameters (currently unused)

Returns:

  • (Hash)

    A new hash with all values converted via as_json



63
64
65
66
67
68
69
70
71
72
# File 'lib/familia/refinements/dear_json.rb', line 63

def as_json(options = nil)
  # Create a new hash, calling as_json on each value.
  transform_values do |value|
    if value.respond_to?(:as_json)
      value.as_json(options)
    else
      value
    end
  end
end

#to_json(options = nil) ⇒ String

Convert hash to JSON string using Familia's secure JsonSerializer. This method preprocesses the hash to handle Familia objects properly by calling as_json on any objects that support it.

Parameters:

  • options (Hash) (defaults to: nil)

    Optional parameters (currently unused, for compatibility)

Returns:

  • (String)

    JSON string representation



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/familia/refinements/dear_json.rb', line 43

def to_json(options = nil)
  # Preprocess the hash to handle Familia objects
  processed_hash = transform_values do |value|
    if value.respond_to?(:as_json)
      value.as_json(options)
    else
      value
    end
  end

  Familia::JsonSerializer.dump(processed_hash)
end