Module: Lich::Common::Settings Private

Defined in:
documented/common/settings.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Manages persistent per-script key-value settings stored in a shared SQLite database.

The Settings module is the primary API for .lic scripts to read and write persistent configuration. It uses an in-process cache to avoid repeated database queries, and coordinates with other Lich sessions (separate Ruby processes) through optimistic locking: writes are applied to the row as it exists in the database now, and stored only if no other session changed the row in between. Writes through SettingsProxy objects (containers returned by Settings) are replayed on the stored row when possible, so that concurrent changes to the same settings coexist.

All settings are stored per (script_name, scope) pair in the script_auto_settings table. The default scope is ":" (colon); scripts can partition their settings by passing a different scope (e.g. "#XMLData.game:#XMLData.name" for per-character settings).

Examples:

Read and write a setting

Settings[:my_key] = "value"
value = Settings[:my_key]

Access nested settings with navigation

Settings.my_setting.nested_key = 42

Write to a container (Hash or Array)

list = Settings[:my_list]
list.push("item")

Defined Under Namespace

Classes: CircularReferenceError

Constant Summary collapse

LOG_LEVEL_NONE =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Logging Configuration

0
LOG_LEVEL_ERROR =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

1
LOG_LEVEL_INFO =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

2
LOG_LEVEL_DEBUG =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

3
DEFAULT_SCOPE =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

":".freeze
REPLAY_ENTRY_CHANGES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

The operation save_proxy_changes replays for a method outside both of SettingsProxy's method lists that changed several entries of a container (SettingsProxy#save_changes_since). Its one argument is the list of [operation, args] entry changes ([:delete, [key]] or [:[]=, [key_or_index, value]]); they are all applied, in order, in one update of the row (see #replay_entry_changes).

:replay_entry_changes
REPLAY_AT_POSITIONS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

The operation save_proxy_changes replays for an Array method whose arguments include a position (SettingsProxy::POSITION_METHODS). Its arguments are [size, first_changed, method, args]: the size of this session's copy before the call, the first position the call changed in that copy (nil when it changed none), and the call itself, its positions counted from the start of that copy (see #replay_at_positions).

:replay_at_positions
@@log_level =

This classvariable is part of a private API. You should avoid using this classvariable if possible, as it may be removed or be changed in the future.

Default: logging disabled

LOG_LEVEL_NONE
@@log_prefix =

This classvariable is part of a private API. You should avoid using this classvariable if possible, as it may be removed or be changed in the future.

"[SettingsModule]".freeze

Class Method Summary collapse

Class Method Details

.[](name) ⇒ Object, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Retrieves a value from the settings by key.

If the value is a Hash or Array, it is wrapped in a SettingsProxy so that mutations (push, []=, delete, etc.) can be persisted. If the key is missing or the value is nil, subsequent chained calls (e.g., Settings[:nested]) silently return nil instead of raising (safe navigation).

Examples:

Settings[:my_key] = "hello"
Settings[:my_key] #=> "hello"
list = Settings[:my_list] = [1, 2, 3]
list.class #=> Lich::Common::SettingsProxy

Parameters:

  • name (String, Symbol) —

    the key to look up

Returns:

  • (Object, SettingsProxy, nil) —

    the value at name, wrapped in a proxy if it is a container; nil if not found



1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
# File 'documented/common/settings.rb', line 1102

def self.[](name)
  scope_to_use = DEFAULT_SCOPE
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "Settings.[]: name: #{name.inspect}, current_path: #{@path_navigator.path.inspect}, safe_nav: #{@safe_navigation_active}" })

  if @path_navigator.path.empty?
    data_for_scope = current_script_settings(scope_to_use)
    _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "Settings.[] (top-level): data_for_scope (DUP) (object_id: #{data_for_scope.object_id}): #{data_for_scope.inspect}" })
    value = get_value_from_container(data_for_scope, name)
    _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "Settings.[] (top-level): value for '#{name}': #{value.inspect}" })
    if value.nil? && !data_for_scope.is_a?(Array) && (!data_for_scope.is_a?(Hash) || !data_for_scope.key?(name))
      _log(LOG_LEVEL_INFO, @@log_prefix, -> { "Settings.[] (top-level): Key '#{name}' not found or value is nil. Activating safe_navigation." })
      @safe_navigation_active = true
    end
    return reset_path_and_return(wrap_value_if_container(value, scope_to_use, [name]))
  else
    current_target, _ = navigate_to_path(false, scope_to_use)
    _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "Settings.[] (path-based): current_target: #{current_target.inspect}" })
    value = get_value_from_container(current_target, name)
    _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "Settings.[] (path-based): value for '#{name}': #{value.inspect}" })
    new_path = @path_navigator.path + [name]
    if value.nil? && !current_target.is_a?(Array) && (!current_target.is_a?(Hash) || !current_target.key?(name))
      _log(LOG_LEVEL_INFO, @@log_prefix, -> { "Settings.[] (path-based): Key '#{name}' not found or value is nil in path. Activating safe_navigation." })
      @safe_navigation_active = true
    end
    return reset_path_and_return(wrap_value_if_container(value, scope_to_use, new_path))
  end
end

.[]=(name, value) ⇒ Object?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Sets a top-level key in the settings and persists it to the database.

Clears any active safe-navigation state so that the next Settings call will raise normally if a key is missing. If a navigation path is active (from chained Settings calls), the key is written into the container at that path instead of at the root.

Examples:

Settings[:my_key] = "hello"
Settings[:my_key] #=> "hello"

Parameters:

  • name (String, Symbol) —

    the key to set

  • value (Object) —

    the value to store

Returns:

  • (Object, nil) —

    the value on success; nil on failure (write refused or no script name)



1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
# File 'documented/common/settings.rb', line 1143

def self.[]=(name, value)
  scope_to_use = DEFAULT_SCOPE
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "Settings.[]=: name: #{name.inspect}, value: #{value.inspect}, current_path: #{@path_navigator.path.inspect}" })
  @safe_navigation_active = false # Reset safe navigation on assignment

  if @path_navigator.path.empty?
    set_script_settings(scope_to_use, name, value)
  else
    # A navigation path left on the shared navigator (Settings.set_path
    # reaches it through method_missing). The key is written into the
    # container at that path. The path is cleared before the write, so
    # that it can't send another Settings[] call (from any script) under
    # it while the write waits on the database, or after it raises.
    path = @path_navigator.path.dup
    @path_navigator.reset_path
    write_key_under_path(scope_to_use, path, name, value) ? value : nil
  end
end

._log(level, prefix, message_proc) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Internal logging method message_proc is a lambda/proc to delay string construction



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'documented/common/settings.rb', line 106

def self._log(level, prefix, message_proc)
  return unless Lich.respond_to?(:log)
  return unless level <= @@log_level

  level_str = case level
              when LOG_LEVEL_ERROR then "[ERROR]"
              when LOG_LEVEL_INFO  then "[INFO]"
              when LOG_LEVEL_DEBUG then "[DEBUG]"
              else "[UNKNOWN]"
              end

  begin
    message = message_proc.call
    Lich.log("#{prefix} #{level_str} #{message}")
  rescue => e
    Lich.log("#{prefix} [ERROR] Logging failed: #{e.message} - Original message proc: #{message_proc.source_location if message_proc.respond_to?(:source_location)}")
  end
end

._reattach_live!(proxy, method = nil) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Internal non-destructive correction method (issue from Lich 5.12.6) non-destructive methods (.sort) cannot own a proxy that requires update (.push)

Binds proxy, a detached view with a path (what sort or select returned), to the container at its path in the row of the proxy's own script (InstanceSettings has its own) as stored now, so that the destructive method about to be called through it changes that container and is stored there (list.sort.push(4) appends 4 to list).

When the stored row holds nothing there (another session removed the container, or a container on the way), the view is bound to this session's copy of the container it was taken from, when that is of the view's kind, and the call is stored from that copy, as through a proxy for the container itself (Settings.push(4) after another session removed list stores this session's list with 4 appended).

The path is passed to the navigator, not set on it: the navigator is shared by every script's Settings calls, and a path left on it would send the next top-level write somewhere else.

Returns false, binding nothing, and tells the user, when the stored row holds a container of another kind there (a Hash where values returned an Array) or something that is not a container, or holds nothing there and the copy the view was taken from is of another kind.



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'documented/common/settings.rb', line 150

def self._reattach_live!(proxy, method = nil)
  script_name = proxy_script_name(proxy)
  scope       = proxy.scope
  path        = proxy.path

  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "reattach_live!: scope=#{scope.inspect} path=#{path.inspect}" })

  live, _root = @path_navigator.navigate_to_path(script_name, false, scope, path)
  if live.nil?
    own_copy = proxy.__send__(:view_source)
    live = own_copy if own_copy.instance_of?(proxy.target.class)
  end

  unless live.instance_of?(proxy.target.class)
    _log(LOG_LEVEL_ERROR, @@log_prefix, -> { "reattach_live!: failed to resolve live target for path=#{path.inspect} scope=#{scope.inspect}" })
    what = live.nil? ? "nothing there" : "#{live.class} there, and the view is #{proxy.target.class}"
    refuse_proxy_save(script_name, proxy, "#{method || "the call"} on a view (sort, select, values, ...) of #{path.inspect} was not applied: the settings hold #{what}", kind: :view_not_applied)
    return false
  end

  # Swap the proxy onto the live object via SettingsProxy API (encapsulated)
  # Centralizes invariants/logging within SettingsProxy itself. The
  # rebinding (and view_source) is private to SettingsProxy; this is
  # its one caller.
  proxy.__send__(:rebind_to_live!, live)
  true
end

.auto ⇒ nil

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deprecated.

This method has no effect; scripts should not use it

Legacy no-op method; retained for backward compatibility.

Returns:

  • (nil)


1383
1384
1385
1386
1387
# File 'documented/common/settings.rb', line 1383

def self.auto
  Lich.deprecated('Settings.auto', 'not using, not applicable,', caller[0], fe_log: true) if Lich.respond_to?(:deprecated)
  _log(LOG_LEVEL_INFO, @@log_prefix, -> { "Settings.auto called (legacy deprecated no-op)." })
  nil
end

.auto=(_val) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deprecated.

This method has no effect; scripts should not use it

Legacy no-op method; retained for backward compatibility.

Parameters:

  • _val (Object) —

    ignored

Returns:

  • (Object) —

    the argument, unchanged



1374
1375
1376
1377
# File 'documented/common/settings.rb', line 1374

def self.auto=(_val)
  Lich.deprecated('Settings.auto=(val)', 'not using, not applicable,', caller[0], fe_log: true) if Lich.respond_to?(:deprecated)
  _log(LOG_LEVEL_INFO, @@log_prefix, -> { "Settings.auto= called (legacy deprecated no-op)." })
end

.autoload ⇒ nil

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deprecated.

This method has no effect; scripts should not use it

Legacy no-op method; retained for backward compatibility.

Returns:

  • (nil)


1393
1394
1395
1396
1397
# File 'documented/common/settings.rb', line 1393

def self.autoload
  Lich.deprecated('Settings.autoload', 'not using, not applicable,', caller[0], fe_log: true) if Lich.respond_to?(:deprecated)
  _log(LOG_LEVEL_INFO, @@log_prefix, -> { "Settings.autoload called (legacy deprecated no-op)." })
  nil
end

.clear ⇒ nil

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deprecated.

This method has no effect; scripts should not use it

Legacy no-op method; retained for backward compatibility.

Returns:

  • (nil)


1363
1364
1365
1366
1367
# File 'documented/common/settings.rb', line 1363

def self.clear
  Lich.deprecated('Settings.clear', 'not using, not applicable,', caller[0], fe_log: true) if Lich.respond_to?(:deprecated)
  _log(LOG_LEVEL_INFO, @@log_prefix, -> { "Settings.clear called (legacy deprecated no-op)." })
  nil
end

.container?(value) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Checks whether a value is a container (Hash or Array).

Parameters:

  • value (Object) —

    the value to check

Returns:

  • (Boolean) —

    true if value is a Hash or Array, false otherwise



257
258
259
# File 'documented/common/settings.rb', line 257

def self.container?(value)
  value.is_a?(Hash) || value.is_a?(Array)
end

.current_script_settings(scope = DEFAULT_SCOPE, script_name: nil) ⇒ Hash, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns this session's cached copy of the settings for a script and scope.

The result is a shallow copy of the cached root object: its top-level Hash or Array is new, but containers within it are shared with the cache. Modifying nested containers modifies the cache; top-level replacements do not. To persist changes, use Settings= or a method on a SettingsProxy returned by Settings.

Parameters:

  • scope (String) (defaults to: DEFAULT_SCOPE) —

    the scope to read; defaults to DEFAULT_SCOPE (":")

  • script_name (String, nil) (defaults to: nil) —

    the script namespace; defaults to Script.current.name

Returns:

  • (Hash, Array, Object) —

    a shallow copy of the cached settings



707
708
709
710
711
712
# File 'documented/common/settings.rb', line 707

def self.current_script_settings(scope = DEFAULT_SCOPE, script_name: nil)
  # Use provided script_name or fall back to Script.current.name
  script_name = script_name || Script.current.name
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "current_script_settings: Request for scope: #{scope.inspect}, script_name: #{script_name.inspect}" })
  cached_root(script_name, scope).dup
end

.db_adapter ⇒ DatabaseAdapter

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The adapter for the shared script_auto_settings table. For core code that needs a fresh read or an atomic write, which the cached Settings API doesn't offer (see DRBanking).

Returns:



248
249
250
# File 'documented/common/settings.rb', line 248

def self.db_adapter
  @db_adapter
end

.get_log_level ⇒ Integer

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the current logging level for the Settings module.

Returns:

  • (Integer) —

    the log level: 0 (none), 1 (error), 2 (info), or 3 (debug)



100
101
102
# File 'documented/common/settings.rb', line 100

def self.get_log_level
  @@log_level
end

.get_scoped_setting(scope_string, key_name, script_name: nil) ⇒ Object, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Retrieves a value from a specific scope, optionally from another script.

Like Settings, but allows reading from a different scope or another script's namespace. Containers are wrapped in SettingsProxy. If the key is missing or nil, the return supports safe nil navigation (subsequent chained calls return nil).

Examples:

Lich::Common::Settings.get_scoped_setting("game:character", :preferences) #=> SettingsProxy

Parameters:

  • scope_string (String) —

    the scope to read

  • key_name (String, Symbol) —

    the key to look up, or nil to return the entire scope

  • script_name (String, nil) (defaults to: nil) —

    the script namespace; defaults to Script.current.name

Returns:

  • (Object, SettingsProxy, nil) —

    the value, wrapped in a proxy if it is a container; nil if not found



1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
# File 'documented/common/settings.rb', line 1272

def self.get_scoped_setting(scope_string, key_name, script_name: nil)
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "get_scoped_setting: scope: #{scope_string.inspect}, key: #{key_name.inspect}, script_name: #{script_name.inspect}" })
  data_for_scope = current_script_settings(scope_string, script_name: script_name)
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "get_scoped_setting: data_for_scope (DUP) (object_id: #{data_for_scope.object_id}): #{data_for_scope.inspect}" })
  value = get_value_from_container(data_for_scope, key_name)
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "get_scoped_setting: value for '#{key_name}': #{value.inspect}" })

  if value.nil? && key_name
    key_absent_in_hash = data_for_scope.is_a?(Hash) && !data_for_scope.key?(key_name)
    key_invalid_for_array = data_for_scope.is_a?(Array) && (!key_name.is_a?(Integer) || key_name < 0 || key_name >= data_for_scope.length)

    if key_absent_in_hash || key_invalid_for_array || (data_for_scope.nil? || (data_for_scope.is_a?(Hash) && data_for_scope.empty?))
      _log(Settings::LOG_LEVEL_INFO, @@log_prefix, -> { "get_scoped_setting: Key '#{key_name}' not found in scope '#{scope_string}'. Value will be nil, supporting '|| default' idiom." })
    end
  end
  wrap_value_if_container(value, scope_string, key_name ? [key_name] : [], script_name: script_name)
end

.get_value_from_container(container, key) ⇒ Object?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Retrieves a value from a container (Hash or Array) by key or index.

Parameters:

  • container (Hash, Array, Object) —

    the container to index

  • key (Object) —

    the key (for Hash) or index (for Array)

Returns:

  • (Object, nil) —

    the value at key/index, or nil if the key is invalid or not found



1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
# File 'documented/common/settings.rb', line 1442

def self.get_value_from_container(container, key)
  if container.is_a?(Hash)
    container[key]
  elsif container.is_a?(Array) && key.is_a?(Integer)
    container[key]
  elsif container.is_a?(Array) && !key.is_a?(Integer)
    _log(LOG_LEVEL_ERROR, @@log_prefix, -> { "get_value_from_container: Attempted to access Array with non-Integer key: #{key.inspect}" })
    nil
  else
    nil
  end
end

.load ⇒ Hash, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deprecated.

Use .refresh_data instead

Legacy method; alias for .refresh_data.

Returns:

  • (Hash, Array, Object) —

    the reloaded settings



1337
1338
1339
1340
# File 'documented/common/settings.rb', line 1337

def self.load
  _log(LOG_LEVEL_INFO, @@log_prefix, -> { "Settings.load called (legacy, aliasing to refresh_data)." })
  refresh_data
end

.method_missing(method, *args, &block) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Delegates navigation and unsafe-method calls to PathNavigator.

Allows syntax like Settings.foo.bar.baz = value to work by building up a path internally. When safe navigation is active (a prior Settings returned nil), assignment operations return nil and read operations return nil without further processing.

Parameters:

  • method (Symbol) —

    the method name

  • args (Array) —

    arguments to the method

  • block (Proc) —

    a block, if provided

Returns:

  • (Object) —

    the result from PathNavigator, or nil if safe navigation is active



1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
# File 'documented/common/settings.rb', line 1412

def self.method_missing(method, *args, &block)
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "method_missing: method: #{method}, args: #{args.inspect}, path: #{@path_navigator.path.inspect}" })
  if @safe_navigation_active && !@path_navigator.path.empty?
    if method.to_s.end_with?("=")
      _log(LOG_LEVEL_ERROR, @@log_prefix, -> { "method_missing: Attempted assignment (#{method}) on a nil path due to safe navigation." })
      return reset_path_and_return(nil)
    end
    return reset_path_and_return(nil)
  end

  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "method_missing: Delegating to path_navigator: #{method}" })
  @path_navigator.send(method, *args, &block)
end

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The value at the navigation path in this process's copy of the row, and that copy. Lich itself only reads through it (create_missing false, from Settings.[]). With create_missing true it creates missing containers in place, in a shallow copy whose containers the cache shares, and stores nothing; a write under a navigation path goes through write_key_under_path instead.



987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
# File 'documented/common/settings.rb', line 987

def self.navigate_to_path(create_missing = true, scope = DEFAULT_SCOPE)
  root_for_scope = current_script_settings(scope)
  return [root_for_scope, root_for_scope] if @path_navigator.path.empty?

  target = root_for_scope
  @path_navigator.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 >= 0 && key < target.length
      target = target[key]
    elsif create_missing && (target.is_a?(Hash) || target.is_a?(Array))
      _log(LOG_LEVEL_INFO, @@log_prefix, -> { "navigate_to_path: Creating missing segment '#{key}' in DUPPED structure for scope #{scope.inspect}" })
      new_node = key.is_a?(Integer) ? [] : {}
      if target.is_a?(Hash)
        target[key] = new_node
      elsif target.is_a?(Array) && key.is_a?(Integer)
        target[key] = new_node
      end
      target = new_node
    else
      return [nil, root_for_scope]
    end
  end
  [target, root_for_scope]
end

.refresh_data(scope = DEFAULT_SCOPE) ⇒ Hash, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Reloads the settings from the database and updates the cache.

Discards the cached row and reads the current one from the database, replacing the cache with it. Useful after another session has made changes you want to see. On database errors, returns the old cached row rather than raising (unless nothing is cached).

Parameters:

  • scope (String) (defaults to: DEFAULT_SCOPE) —

    the scope to refresh; defaults to DEFAULT_SCOPE (":")

Returns:

  • (Hash, Array, Object) —

    a shallow copy of the reloaded settings

See Also:

  • cached_root


947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
# File 'documented/common/settings.rb', line 947

def self.refresh_data(scope = DEFAULT_SCOPE)
  script_name = Script.current.name
  cache_key = "#{script_name || ""}::#{scope}" # Use an empty string if script_name is nil
  _log(LOG_LEVEL_INFO, @@log_prefix, -> { "refresh_data: Reloading cache for scope: #{scope.inspect}, cache_key: #{cache_key}" })
  # Reload under the entry's lock, replacing whatever is cached. A cache
  # miss fill keeps a row another thread cached while it waited, which
  # could be one read before this call began. If the read raises, the
  # cached row and its recorded version stay as they were.
  settings = with_cache_lock(cache_key) do
    version = @db_adapter.data_version
    root = @db_adapter.get_settings(script_name, scope)
    # The version recorded for the old root no longer matches the
    # cached object, so the next read checks the database again (see
    # cached_root). A row another thread re-read after a commit this
    # read may have missed is kept (see store_after_database); this
    # call still returns its own.
    store_after_database(cache_key, root, version, newer_only: true)
    root
  end
  settings.dup
end

.reset_path_and_return(value) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Clears the navigation path and returns the given value.

Used internally after Settings operations to ensure the shared path navigator does not retain a path for the next call.

Parameters:

  • value (Object) —

    the value to return

Returns:

  • (Object) —

    value, unchanged



977
978
979
# File 'documented/common/settings.rb', line 977

def self.reset_path_and_return(value)
  @path_navigator.reset_path_and_return(value)
end

.respond_to_missing?(method_name, include_private = false) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns true for any method delegated to PathNavigator via method_missing.

Parameters:

  • method_name (Symbol, String) —

    the method to check

  • include_private (Boolean) (defaults to: false) —

    whether to include private methods; defaults to false

Returns:

  • (Boolean) —

    true if PathNavigator responds to the method, false otherwise



1432
1433
1434
# File 'documented/common/settings.rb', line 1432

def self.respond_to_missing?(method_name, include_private = false)
  @path_navigator.respond_to?(method_name, include_private) || super
end

.root_proxy_for(scope, script_name: Script.current.name) ⇒ SettingsProxy

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Creates a root-level SettingsProxy for the given scope.

This factory ensures the proxy directly targets the cached root object for the (script_name, scope) pair. By using the cached root, it avoids "identity drift" bugs where the proxy's @target differs from the object being persisted by save_proxy_changes.

Examples:

Create a root proxy for the current character

settings = Lich::Common::Settings.root_proxy_for("#{XMLData.game}:#{XMLData.name}")

Parameters:

  • scope (String) —

    A logical scope identifier (for example, "#XMLData.game:#XMLData.name").

  • script_name (String, nil) (defaults to: Script.current.name) —

    The script namespace; defaults to Script.current.name. Pass nil to fall back to the empty string.

Returns:

Raises:

  • (ArgumentError) —

    if scope is nil or empty.



323
324
325
326
327
328
329
330
# File 'documented/common/settings.rb', line 323

def self.root_proxy_for(scope, script_name: Script.current.name)
  raise ArgumentError, "scope must be a non-empty String" if scope.nil? || scope.to_s.strip.empty?

  script_name ||= ""
  root = cached_root(script_name, scope)

  SettingsProxy.new(self, scope, [], root, script_name: script_name)
end

.save ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Legacy Support Methods



1328
1329
1330
1331
# File 'documented/common/settings.rb', line 1328

def self.save
  _log(LOG_LEVEL_INFO, @@log_prefix, -> { "Settings.save called (legacy no-op)." })
  :noop
end

.save_all ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deprecated No-Op Methods from Original



1353
1354
1355
1356
1357
# File 'documented/common/settings.rb', line 1353

def self.save_all
  Lich.deprecated('Settings.save_all', 'not using, not applicable,', caller[0], fe_log: true) if Lich.respond_to?(:deprecated)
  _log(LOG_LEVEL_INFO, @@log_prefix, -> { "Settings.save_all called (legacy deprecated no-op)." })
  nil
end

.save_proxy_changes(proxy, method = nil, args = [], block = nil, label: nil) ⇒ Array(Object, Hash|Array)?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Saves a change made through proxy without losing what other sessions saved in the meantime, in the same container or elsewhere in the row.

Every Lich session is a separate process, and a proxy holds this session's copy of one container, read some time before the write. So the operation itself (+method+ with args and block, already applied to proxy.target) is applied again to the container at proxy.path in the row as it is stored now, and the row is stored only if no one changed it in between (DatabaseAdapter#update_settings starts over otherwise). Missing containers on the way are created, as before.

This session's copy of the container is stored instead (as every nested write did before) when there is no operation to replay (+method+ nil), when the proxy is a detached view with a path (its contents are not the container's), when the stored row has no container of the proxy's class at its path (another session removed or replaced it), or when the operation raises on the stored container. Nothing is stored, and the user is told, for a detached proxy without a path (a view of a root proxy, the default fetch returned, or a container built from one), nor for the proxy of a view's element that can't be found in the settings (SettingsProxy#unlocated?), nor for a new container built from an element SettingsProxy#each yielded (SettingsProxy#copy?). Nothing is stored either, and the user is told, when block leaves early (break, throw or return), is interrupted or its thread is killed while it runs on the stored container.

On success the cache takes the row as stored, unless another thread has re-read a newer one after the store (see store_after_database). On failure the cache is left as it was, and the next read checks the database again. All of it runs under the cache entry's lock (see with_cache_lock).

Parameters:

  • proxy (SettingsProxy) —

    the proxy the change was made through

  • method (Symbol, nil) (defaults to: nil) —

    the operation applied to proxy.target, or REPLAY_ENTRY_CHANGES for the entries a script's call changed

  • args (Array) (defaults to: []) —

    its arguments; they are stored as copies (proxies unwrapped, everything copied as a read of the stored row would give it back), so the stored and cached row share no object with them

  • block (Proc, nil) (defaults to: nil) —

    its block

  • label (Symbol, nil) (defaults to: nil) —

    the script's method that made the change, named in messages (defaults to method)

Returns:

  • (Array(Object, Hash|Array), nil) —

    when the operation was replayed and stored: its result on the stored container, and that container (part of the row now cached); nil otherwise



377
378
379
380
# File 'documented/common/settings.rb', line 377

def self.save_proxy_changes(proxy, method = nil, args = [], block = nil, label: nil)
  script_name = proxy_script_name(proxy)
  with_cache_lock("#{script_name || ""}::#{proxy.scope}") { store_proxy_changes(proxy, script_name, method, args, block, label) }
end

.save_to_database(data_to_save, scope = DEFAULT_SCOPE, script_name: nil) ⇒ Boolean?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Saves a whole row and caches it (see store_after_database).

Returns:

  • (Boolean, nil) —

    whether the cache took the saved row (false when a newer row another thread re-read after the save is kept), or nil when nothing was saved for lack of a script name



907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
# File 'documented/common/settings.rb', line 907

def self.save_to_database(data_to_save, scope = DEFAULT_SCOPE, script_name: nil)
  # Use provided script_name or fall back to Script.current.name
  script_name = script_name || Script.current.name

  if script_name.nil? || script_name.empty?
    _log(LOG_LEVEL_ERROR, @@log_prefix, -> { "save_to_database: Aborting save. script_name is nil or empty. Scope: #{scope.inspect}. Data will NOT be persisted." })
    return nil # Explicitly return nil
  end

  cache_key = "#{script_name}::#{scope}" # script_name is guaranteed to be non-nil/non-empty here
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "save_to_database: Saving for script: '#{script_name}', scope: #{scope.inspect}, cache_key: #{cache_key}" })
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "save_to_database: Data BEFORE unwrap_proxies (object_id: #{data_to_save.object_id}): #{data_to_save.inspect}" })

  unwrapped_settings = unwrap_proxies(data_to_save)
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "save_to_database: Data AFTER unwrap_proxies (object_id: #{unwrapped_settings.object_id}): #{unwrapped_settings.inspect}" })

  with_cache_lock(cache_key) do
    @db_adapter.save_settings(script_name, unwrapped_settings, scope)
    _log(LOG_LEVEL_INFO, @@log_prefix, -> { "save_to_database: Data saved to DB for script '#{script_name}'." })

    if store_after_database(cache_key, unwrapped_settings, @db_adapter.data_version)
      _log(LOG_LEVEL_INFO, @@log_prefix, -> { "save_to_database: Cache updated for #{cache_key} with saved data (object_id: #{unwrapped_settings.object_id})." })
      true
    else
      _log(LOG_LEVEL_INFO, @@log_prefix, -> { "save_to_database: Kept the newer row another thread re-read for #{cache_key} after the save." })
      false
    end
  end
end

.set_log_level(level) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Sets the logging verbosity for the Settings module.

Examples:

Lich::Common::Settings.set_log_level(:debug)

Parameters:

  • level (Integer, Symbol) —

    the log level: :none or 0 (disabled), :error or 1, :info or 2, :debug or 3. Invalid levels default to :none and log an error.



83
84
85
86
87
88
89
90
91
92
93
94
# File 'documented/common/settings.rb', line 83

def self.set_log_level(level)
  numeric_level = case level
                  when :none, LOG_LEVEL_NONE then LOG_LEVEL_NONE
                  when :error, LOG_LEVEL_ERROR then LOG_LEVEL_ERROR
                  when :info, LOG_LEVEL_INFO then LOG_LEVEL_INFO
                  when :debug, LOG_LEVEL_DEBUG then LOG_LEVEL_DEBUG
                  else
                    _log(LOG_LEVEL_ERROR, @@log_prefix, -> { "Invalid log level specified: #{level.inspect}. Defaulting to NONE." })
                    LOG_LEVEL_NONE
                  end
  @@log_level = numeric_level
end

.set_script_settings(scope = DEFAULT_SCOPE, name, value, script_name: nil) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Writes a top-level key in the settings and persists it to the database.

Parameters:

  • scope (String) (defaults to: DEFAULT_SCOPE) —

    the scope to write to; defaults to DEFAULT_SCOPE (":")

  • name (String, Symbol) —

    the key to set

  • value (Object) —

    the value to store; proxies are unwrapped first

  • script_name (String, nil) (defaults to: nil) —

    the script namespace; defaults to Script.current.name

Returns:

  • (Object) —

    the value, on success; nil on failure



1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
# File 'documented/common/settings.rb', line 1021

def self.set_script_settings(scope = DEFAULT_SCOPE, name, value, script_name: nil)
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "set_script_settings: scope: #{scope.inspect}, name: #{name.inspect}, value: #{value.inspect}, script_name: #{script_name.inspect}, current_path: #{@path_navigator.path.inspect}" })
  unwrapped_value = unwrap_proxies(value)
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "set_script_settings: unwrapped_value: #{unwrapped_value.inspect}" })

  unless @path_navigator.path.empty?
    _log(LOG_LEVEL_ERROR, @@log_prefix, -> { "set_script_settings: WARNING: Called with non-empty path_navigator path: #{@path_navigator.path.inspect}. This is unusual for Char/GameSettings direct assignment." })
  end

  write_top_level_key(scope, name, unwrapped_value, script_name: script_name)
  reset_path_and_return(value)
end

.to_h(scope = DEFAULT_SCOPE) ⇒ Hash, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Deprecated.

Use .to_hash instead

Legacy method; alias for .to_hash.

Parameters:

  • scope (String) (defaults to: DEFAULT_SCOPE) —

    the scope to read; defaults to DEFAULT_SCOPE (":")

Returns:

  • (Hash, Array, Object) —

    the settings, deep-copied, with no proxies



1347
1348
1349
1350
# File 'documented/common/settings.rb', line 1347

def self.to_h(scope = DEFAULT_SCOPE) # Added scope to match to_hash for consistency if used directly
  _log(LOG_LEVEL_INFO, @@log_prefix, -> { "Settings.to_h called (legacy, aliasing to to_hash)." })
  self.to_hash(scope)
end

.to_hash(scope = DEFAULT_SCOPE) ⇒ Hash, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the settings for a scope as a plain Hash or Array, with all proxies unwrapped.

This is a snapshot: the returned object shares no containers with the cache, so modifications do not affect future Settings reads.

Parameters:

  • scope (String) (defaults to: DEFAULT_SCOPE) —

    the scope to read; defaults to DEFAULT_SCOPE (":")

Returns:

  • (Hash, Array, Object) —

    the settings, deep-copied, with no proxies



1319
1320
1321
1322
1323
1324
1325
# File 'documented/common/settings.rb', line 1319

def self.to_hash(scope = DEFAULT_SCOPE)
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "to_hash: scope: #{scope.inspect}" })
  data = current_script_settings(scope)
  unwrapped_data = unwrap_proxies(data)
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "to_hash: Returning unwrapped data (snapshot): #{unwrapped_data.inspect}" })
  return unwrapped_data
end

.with_proxy_lock(proxy, &block) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Runs the block holding the lock of +proxy+'s cache entry, the one save_proxy_changes takes (see with_cache_lock). SettingsProxy holds it from the change to its copy until it shows the stored container, so that two threads writing through proxies of one entry show the stored containers in the order they were stored: a slower thread can't put an older one over a newer one.



388
389
390
# File 'documented/common/settings.rb', line 388

def self.with_proxy_lock(proxy, &block)
  with_cache_lock("#{proxy_script_name(proxy) || ""}::#{proxy.scope}", &block)
end

.wrap_value_if_container(value, scope, path_array, script_name: nil) ⇒ Object, SettingsProxy

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Wraps a value in a SettingsProxy if it is a Hash or Array.

Used internally when returning values from Settings and related methods to ensure that mutations on containers are persisted.

Parameters:

  • value (Object) —

    the value to potentially wrap

  • scope (String) —

    the scope for the proxy

  • path_array (Array) —

    the path within that scope

  • script_name (String, nil) (defaults to: nil) —

    the script namespace for InstanceSettings, if any

Returns:

  • (Object, SettingsProxy) —

    the wrapped value (if a container) or the original value



1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
# File 'documented/common/settings.rb', line 1301

def self.wrap_value_if_container(value, scope, path_array, script_name: nil)
  _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "wrap_value_if_container: value_class: #{value.class}, scope: #{scope.inspect}, path: #{path_array.inspect}, script_name: #{script_name.inspect}" })
  if container?(value)
    proxy = SettingsProxy.new(self, scope, path_array, value, script_name: script_name)
    _log(LOG_LEVEL_DEBUG, @@log_prefix, -> { "wrap_value_if_container: Wrapped in proxy: #{proxy.inspect}" })
    return proxy
  else
    return value
  end
end