Adjusting Strategies
=begin rakudoc
Overview
Strategies add behavior to traversal without changing the data model walker.
Use this extension point when the walker can already traverse the data, but an extension needs custom behavior before elements, after elements, when elements match, or when deciding whether to follow relations.
To adjust strategy behavior:
1. Setup: decide which traversal hook should change behavior.
2. Hooks: implement the needed
Qwiratry::Strategy::Strategymethods.3. Control Signals: return standard control values for pruning or stopping traversal.
4. Finish Results: return a
FinishResultwhen traversal has a meaningful outcome.5. Testing: test hooks under a real walker.
Setup
Use a strategy when traversal already knows how to visit the data, but the extension needs to observe, prune, stop, aggregate, or repeat traversal.
Do not use a strategy to teach Qwiratry how to traverse a new data model. That belongs in a walker.
Do not use a strategy to parse or render external data. That belongs in a format.
Hooks
Hook Model
A strategy may implement any of these hooks:
before($element, Context $ctx)
Called before visiting an element.
on-match($element, QueryMatch $match, Context $ctx)
Called when a query matches an element.
should-follow($origin, $relation, $target, Context $ctx)
Returns whether traversal should follow a relation.
after($element, Context $ctx)
Called after an element and its relations are processed.
finish($root, Context $ctx)
Called after traversal completes.
should-continue($root, Context $ctx)
Returns whether another traversal pass should run.
Minimal Strategy Example
use Qwiratry::Strategy;
use Qwiratry::Strategy::FinishResult;
class CollectingStrategy does Strategy {
has @.matches;
method on-match($element, $match, $ctx) {
@!matches.push($element);
Nil
}
method finish($root, $ctx --> FinishResult) {
FinishResult.new(type => 'matches', value => @!matches.List)
}
}
Control Signals
Hooks may return control values such as SKIP_ELEMENT or
STOP_TRAVERSAL. These are handled by Qwiratry::Strategy::TraversalState.
Finish Results
Return Qwiratry::Strategy::FinishResult::FinishResult from finish when the
strategy has a meaningful result to report after traversal completes.
Testing
Add tests that prove:
Hooks are called in the expected order.
should-followprunes traversal when it returnsFalse.Control signals such as
SKIP_ELEMENTandSTOP_TRAVERSALare honored.finishreturns the expectedFinishResult.Strategy behavior works under at least one concrete walker.
Reference Material
Main Types
Qwiratry::Strategy::Strategy
Role implemented by custom strategies.
Qwiratry::Strategy::FinishResult::FinishResult
Return object from finish.
Qwiratry::Strategy::RewriteSpec::RewriteSpec
Marker role for rewrite payloads returned from strategy hooks.
Qwiratry::Strategy::Traversal
Shared dispatcher for calling strategy hooks consistently.
Qwiratry::Strategy::TraversalState
Mutable control state used while strategy hooks run.
=end rakudoc