Class: Lich::Common::PathNavigator

Inherits:
Object
  • Object
show all
Defined in:
lib/common/settings/path_navigator.rb

Overview

Path navigator to encapsulate path navigation logic

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(db_adapter) ⇒ PathNavigator

Initializes a new PathNavigator instance.

Parameters:

  • db_adapter (Object)

    The database adapter used for retrieving settings.



8
9
10
11
# File 'lib/common/settings/path_navigator.rb', line 8

def initialize(db_adapter)
  @db_adapter = db_adapter
  @path = []
end

Instance Attribute Details

#pathArray (readonly)

Returns the current path.

Returns:

  • (Array)

    The current path as an array.



16
17
18
# File 'lib/common/settings/path_navigator.rb', line 16

def path
  @path
end

Instance Method Details

Navigates to a specified path based on the script name and scope.

Examples:

navigator = Lich::Common::PathNavigator.new(db_adapter)
target, root = navigator.navigate_to_path("script_name")

Parameters:

  • script_name (String)

    The name of the script to navigate.

  • create_missing (Boolean) (defaults to: true)

    Whether to create missing path elements (default: true).

  • scope (String) (defaults to: ":")

    The scope to use for retrieving settings (default: “:”).

Returns:

  • (Array)

    An array containing the target value and the root value.

Raises:

  • (KeyError)

    If the key does not exist and create_missing is false.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/common/settings/path_navigator.rb', line 44

def navigate_to_path(script_name, create_missing = true, scope = ":")
  root = @db_adapter.get_settings(script_name, scope)
  return [root, root] if @path.empty?

  target = root
  @path.each do |key|
    if target.is_a?(Hash) && target.key?(key)
      target = target[key]
    elsif target.is_a?(Array) && key.is_a?(Integer) && key < target.length
      target = target[key]
    elsif create_missing
      # Path doesn't exist yet, create it
      target[key] = key.is_a?(Integer) ? [] : {}
      target = target[key]
    else
      # Path doesn't exist and we're not creating it
      return [nil, root]
    end
  end

  [target, root]
end

#reset_pathvoid

This method returns an undefined value.

Resets the path to an empty array.



21
22
23
# File 'lib/common/settings/path_navigator.rb', line 21

def reset_path
  @path = []
end

#reset_path_and_return(value) ⇒ Object

Resets the path and returns the provided value.

Parameters:

  • value (Object)

    The value to return after resetting the path.

Returns:

  • (Object)

    The provided value.



29
30
31
32
# File 'lib/common/settings/path_navigator.rb', line 29

def reset_path_and_return(value)
  reset_path
  value
end