Module: OpnApi::Normalize

Defined in:
lib/opn_api/normalize.rb

Overview

Normalization of OPNsense selection hashes.

OPNsense returns multi-select/dropdown fields as hashes like:

{ "opt1" => { "value" => "Option 1", "selected" => 1 },
  "opt2" => { "value" => "Option 2", "selected" => 0 } }

This module collapses them to comma-separated strings of selected keys (e.g. “opt1”) and recurses into nested hashes.

Class Method Summary collapse

Class Method Details

.normalize_config(obj) ⇒ Object

Recursively normalizes OPNsense selection hashes to simple values.

Parameters:

  • obj (Object)

    The value to normalize

Returns:

  • (Object)

    Normalized value



19
20
21
22
23
24
# File 'lib/opn_api/normalize.rb', line 19

def normalize_config(obj)
  return obj unless obj.is_a?(Hash)
  return normalize_selection(obj) if selection_hash?(obj)

  obj.transform_values { |v| normalize_config(v) }
end

.normalize_selection(hash) ⇒ String

Collapses a selection hash to a comma-separated string of selected keys.

Parameters:

  • hash (Hash)

    A selection hash (as detected by selection_hash?)

Returns:

  • (String)

    Comma-separated selected keys



43
44
45
# File 'lib/opn_api/normalize.rb', line 43

def normalize_selection(hash)
  hash.select { |_k, v| v['selected'].to_i == 1 }.keys.join(',')
end

.selection_hash?(hash) ⇒ Boolean

Detects whether a hash is an OPNsense selection hash.

A selection hash has non-empty entries where every value is a Hash containing at least ‘value’ and ‘selected’ keys.

Parameters:

  • hash (Hash)

Returns:

  • (Boolean)


33
34
35
36
37
# File 'lib/opn_api/normalize.rb', line 33

def selection_hash?(hash)
  hash.is_a?(Hash) &&
    !hash.empty? &&
    hash.values.all? { |v| v.is_a?(Hash) && v.key?('value') && v.key?('selected') }
end