CodeSampleX

Ejemplo

mustermann 4.0.0: Extract route parameters incrementally using peek_params and compose patterns safely using safe_string and the plus operator

Muestra verificada para gem mustermann 4.0.0: Extract route parameters incrementally using peek_params and compose patterns safely using safe_string and the…

sha256:117b6e942fe9e37e5690f53de7efe111bb81d17d64ed24e9fcd18ae4827199c3

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
2
Entorno declarado ruby linux x64 ruby ruby bundler

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-17
ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-18

Caso

HOW
Objetivo
Extract route parameters incrementally using peek_params and compose patterns safely using safe_string and the plus operator
Paquetes
Símbolos
  • Mustermann
  • Mustermann.new
  • Mustermann::Pattern#peek_params
  • Mustermann::Pattern#safe_string
  • Mustermann::Pattern#+
Entorno
ruby
Creado
2026-08-17T07:28:24Z

Contrato

  1. Mustermann patterns anchored to string boundaries return nil on subpaths when using match or params, but peek_params performs unanchored prefix matching and returns both extracted params and the consumed character offset for stepwise sub-routing.
  2. Slicing the input path by the consumed character offset allows feeding the remaining subpath directly into downstream Mustermann patterns.
  3. Direct string interpolation of a pattern into a literal suffix mutates the capture identifier into a single combined token.
  4. Calling safe_string produces an RFC 6570 braced template string that protects the parameter name from colliding with adjacent literal characters.
  5. Concatenating patterns with the plus operator natively merges their ASTs into a single Mustermann::Sinatra instance containing both captures.

Archivos

  • Gemfile
  • Gemfile.lock
  • NOTES.md
  • csx.json
  • test/contract.rb

Descargar el artefacto de código fuente (tar.gz)

Código fuente

Gemfile
# frozen_string_literal: true

source "https://rubygems.org"

gem "mustermann", "4.0.0"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    mustermann (4.0.0)

PLATFORMS
  ruby
  x64-mingw-ucrt
  x86_64-linux

DEPENDENCIES
  mustermann (= 4.0.0)

BUNDLED WITH
   2.6.9
NOTES.md
# Mustermann 4.0.0 Prefix Matching and Pattern Composition

## `search_known_solution` Result
`search_known_solution` returned three existing samples for Mustermann 4.0.0:
- `sha256:b93244f63cc31a720f00109506358b78d33bfdbb43bf8e91519ac4a0d276f669`: Pattern memoization via `EqualityMap` and match cache controls.
- `sha256:afb7382535fb243b7a565f691412bed7f98690dabfec4e13d7e188c4ad47f1dc`: Trie routing preference for static routes over earlier dynamic routes in `Mustermann::Set`.
- `sha256:082e43ae1a14d53e8b7ca2cdca58e1ee1317439aeb2a675749b1254de6084a84`: Wildcard path capture handling for empty segments.

None of those samples prove incremental prefix consumption via `peek_params`, the identifier collision trap during string interpolation, or native AST fusion via the `+` operator.

## Exact Release Pinned
- `mustermann` `4.0.0`

## Observed Behavior
1. **Anchored vs Prefix Matching**:
   `Mustermann.new` compiles regular expressions with full-string anchors (`\A ... \z`). Calling `pattern.match(path)` or `pattern.params(path)` returns `nil` whenever the path contains unconsumed trailing subpaths.
   To process paths incrementally across hierarchical routers, `Mustermann` provides `pattern.peek_params(path)`, which matches the prefix without anchoring and returns a two-element tuple `[params_hash, consumed_char_count]`. The caller can slice the input string `path[consumed_char_count..-1]` to pass the remainder to downstream patterns.

2. **String Interpolation Token Collision vs `safe_string`**:
   Standard string interpolation `"\#{pattern}suffix"` invokes `to_s` (producing e.g. `"/api/:version"`). When concatenated directly to `"_ext"`, Mustermann parses `"/:version_ext"` as a single capture token named `"version_ext"`.
   To prevent token collision, `pattern.safe_string` outputs an RFC 6570 braced template string (`"/api/{version}"`), ensuring adjacent characters become literal tokens rather than modifying the capture name.

3. **Native AST Fusion with `+`**:
   Adding two pattern instances via `pattern1 + pattern2` merges their abstract syntax trees natively into a single unified `Mustermann::Sinatra` pattern object instead of a composite evaluation wrapper.

## How the Wrong Expectation Fails
- A model expecting `match` or `params` to match route prefixes fails loudly with `nil` exceptions when attempting sub-routing.
- A model interpolating pattern strings into sub-route paths fails silently with altered capture keys (e.g. `params["version_ext"]` instead of `params["version"]`).
csx.json
{"case":{"believed":"Mustermann pattern matching always requires full string matches, and string interpolation of pattern objects safely preserves named parameter boundaries without altering AST capture names.","caseId":"case:sha256:d071b9a44415622b503f7dc3a194e8ee7eded2b6d8813019ccd127241f217215","contract":["Mustermann patterns anchored to string boundaries return nil on subpaths when using match or params, but peek_params performs unanchored prefix matching and returns both extracted params and the consumed character offset for stepwise sub-routing.","Slicing the input path by the consumed character offset allows feeding the remaining subpath directly into downstream Mustermann patterns.","Direct string interpolation of a pattern into a literal suffix mutates the capture identifier into a single combined token.","Calling safe_string produces an RFC 6570 braced template string that protects the parameter name from colliding with adjacent literal characters.","Concatenating patterns with the plus operator natively merges their ASTs into a single Mustermann::Sinatra instance containing both captures."],"goal":"Extract route parameters incrementally using peek_params and compose patterns safely using safe_string and the plus operator","kind":"HOW","packages":["pkg:gem/mustermann@4.0.0"],"schemaVersion":1,"symbols":["Mustermann","Mustermann.new","Mustermann::Pattern#peek_params","Mustermann::Pattern#safe_string","Mustermann::Pattern#+"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"bundler","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/mustermann@4.0.0"],"schemaVersion":1,"symbols":["Mustermann","Mustermann.new","Mustermann::Pattern#peek_params","Mustermann::Pattern#safe_string","Mustermann::Pattern#+"],"verifierAdapter":"rubygems@1"}
test/contract.rb
# frozen_string_literal: true

require 'mustermann'

# 1. Full-string matching is strictly anchored:
# Mustermann.new creates patterns anchored to string boundaries (\A ... \z),
# so match and params return nil when evaluated against nested subpaths.
prefix_pattern = Mustermann.new('/api/:version')
sub_pattern = Mustermann.new('/users/:user_id')
full_path = '/api/v1/users/42/details'

raise 'Expected anchored match to return nil for subpath' unless prefix_pattern.match(full_path).nil?
raise 'Expected anchored params to return nil for subpath' unless prefix_pattern.params(full_path).nil?

# 2. Incremental prefix consumption with peek_params:
# peek_params performs unanchored prefix matching and returns [params, consumed_size],
# enabling stepwise path consumption without manual regex splitting.
prefix_params, consumed = prefix_pattern.peek_params(full_path)
raise 'Expected peek_params to extract version param' unless prefix_params == { 'version' => 'v1' }
raise 'Expected peek_params to report consumed prefix length of 7' unless consumed == 7

# 3. Chaining remaining path slice to subsequent pattern:
remaining_path = full_path[consumed..-1]
raise 'Expected remaining path to be /users/42/details' unless remaining_path == '/users/42/details'

user_params, sub_consumed = sub_pattern.peek_params(remaining_path)
raise 'Expected sub_pattern peek_params to extract user_id' unless user_params == { 'user_id' => '42' }
raise 'Expected sub_pattern to consume 9 characters' unless sub_consumed == 9

tail_path = remaining_path[sub_consumed..-1]
raise 'Expected tail path to be /details' unless tail_path == '/details'

# 4. AST-safe interpolation via safe_string vs unsafe to_s:
# Naive string interpolation "#{pattern}suffix" merges capture identifier with the literal suffix,
# converting :version into :version_ext.
unsafe_interpolated = Mustermann.new("#{prefix_pattern}_ext")
raise 'Expected unsafe interpolation to merge identifier into version_ext' unless unsafe_interpolated.names == ['version_ext']
raise 'Expected unsafe interpolation to match full mutated identifier' unless unsafe_interpolated.params('/api/v1_ext') == { 'version_ext' => 'v1_ext' }

# safe_string wraps captures in braces (/{version}) to preserve identifier boundaries.
safe_interpolated = Mustermann.new("#{prefix_pattern.safe_string}_ext")
raise 'Expected safe_string interpolation to preserve version capture name' unless safe_interpolated.names == ['version']
raise 'Expected safe_string to isolate parameter value from literal suffix' unless safe_interpolated.params('/api/v1_ext') == { 'version' => 'v1' }

# 5. Native AST concatenation with + operator:
# Adding patterns via + fuses their ASTs into a single Mustermann::Sinatra instance.
fused_pattern = prefix_pattern + sub_pattern
raise 'Expected + to produce a Mustermann::Sinatra instance' unless fused_pattern.is_a?(Mustermann::Sinatra)
raise 'Expected fused pattern to contain both capture names' unless fused_pattern.names == ['version', 'user_id']

fused_params = fused_pattern.params('/api/v1/users/42')
raise 'Expected fused pattern to extract both parameters' unless fused_params == { 'version' => 'v1', 'user_id' => '42' }

puts 'All contract assertions passed successfully.'

Seeder de origen

csx-seed