17 — Advanced

Scoped Bindings

ScopedBindings create a stack of named scopes, each with its own set of bindings. Scopes are layered so that bindings are resolved from the current scope upward through parent scopes. This is ideal for isolating rule execution contexts and managing request-scoped variables.

Creating Scoped Bindings

ScopedBindings scoped = (ScopedBindings) Bindings.builder().scoped();

Scope Layering

Scopes are layered in a stack: root at the bottom, then global, then any user-created scopes on top. When resolving a binding, rulii searches from the current (topmost) scope downward until it finds a match.

ROOT_SCOPE

The bottom-most scope, always present

GLOBAL_SCOPE

Above root, for shared bindings

User Scopes

Added on top via addScope()

Working with Scopes

ScopedBindings scoped = (ScopedBindings) Bindings.builder().scoped();

// Add bindings to root scope
scoped.bind("appName", "MyApp");

// Create a child scope
NamedScope childScope = scoped.addScope("request");
scoped.bind("userId", 42);

// Both are accessible
scoped.getValue("appName");  // "MyApp" (from root)
scoped.getValue("userId");   // 42 (from request scope)

// Remove the child scope
scoped.removeScope();
// "userId" is no longer accessible
// "appName" is still there

Key Methods

Method Description
addScope(name) Push a new named scope onto the stack
removeScope() Pop the current scope from the stack
getCurrentScope() Get the topmost scope
getParentScope() Get the scope below the current one
getRootScope() Get the bottom-most root scope
getGlobalScope() Get the global scope
getScopeSize() Get the number of scopes in the stack
containsScope(name) Check if a named scope exists

Use Cases

Scoped bindings are particularly useful for:

  • Isolating rule execution contexts so rules don't interfere with each other
  • Managing request-scoped variables in web applications
  • Creating temporary binding layers that are discarded after use
  • Sharing global configuration while allowing local overrides