Module: ConstConf::JSONPlugin

Defined in:
lib/const_conf/json_plugin.rb

Overview

A module that provides functionality for loading JSON files or parsing JSON strings as configuration values.

The JSONPlugin module extends the ConstConf::Setting class to enable configuration settings that are either sourced from JSON files on disk or decoded from JSON-formatted environment variables. It ensures a stable, polymorphic representation by using the JSONConfig class for all parsed objects.

Defined Under Namespace

Classes: JSONConfig

Instance Method Summary collapse

Instance Method Details

#json(path = nil, required: false, object_class: JSONConfig) ⇒ JSONConfig, ...

Provides JSON loading or decoding logic based on the presence of a path.

As a Loader (Path provided)

When a path is given, it reads the file from the filesystem and parses its content into a JSONConfig object.

As a Factory (No path provided)

When called without arguments, it returns a Proc that can be used in a decode block to parse JSON strings (e.g., from environment variables).

Parameters:

  • path (String, nil) (defaults to: nil)

    the filesystem path to the JSON file; if omitted, a decoder Proc is returned instead.

  • required (Boolean) (defaults to: false)

    whether the file must exist (only applicable when path is provided), defaults to false.

  • object_class (Class) (defaults to: JSONConfig)

    the class used for parsing JSON objects, defaults to JSONConfig.

Returns:

  • (JSONConfig, Proc, nil)

    returns a parsed JSONConfig (or nil if missing and not required) when path is provided; otherwise, returns a Proc for decoding.

Raises:

  • (ConstConf::RequiredValueNotConfigured)

    if the file does not exist and required is true.



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/const_conf/json_plugin.rb', line 48

def json(path = nil, required: false, object_class: JSONConfig)
  if path
    if File.exist?(path)
      JSON.load_file(path, object_class:)
    elsif required
      raise ConstConf::RequiredValueNotConfigured,
        "JSON file required at path #{path.to_s.inspect}"
    end
  else
    -> value { JSON.parse(value, object_class:) unless value.nil? }
  end
end