alef 0.67.2

Opinionated polyglot binding generator for Rust libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
use super::*;
use crate::core::config::NewAlefConfig;

fn resolve_config(toml_text: &str) -> ResolvedCrateConfig {
    let cfg: NewAlefConfig = toml::from_str(toml_text).expect("valid config");
    cfg.resolve().expect("resolve").remove(0)
}

fn minimal_config() -> ResolvedCrateConfig {
    resolve_config(
        r#"
[workspace]
languages = ["ruby"]
[[crates]]
name = "my-lib"
sources = []
"#,
    )
}

fn zero_arg_function(name: &str, return_type: TypeRef) -> FunctionDef {
    FunctionDef {
        name: name.to_string(),
        return_type,
        ..Default::default()
    }
}

fn simple_field(name: &str, ty: TypeRef) -> FieldDef {
    FieldDef {
        name: name.to_string(),
        ty,
        ..Default::default()
    }
}

fn dto(name: &str, fields: Vec<FieldDef>) -> TypeDef {
    TypeDef {
        name: name.to_string(),
        fields,
        ..Default::default()
    }
}

/// The strongest tier: a visible zero-arg, primitive-returning function is actually
/// invoked across the Magnus boundary, not merely named.
#[test]
fn calls_a_visible_zero_argument_function() {
    let api = ApiSurface {
        functions: vec![zero_arg_function("ping", TypeRef::Primitive(PrimitiveType::Bool))],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(out.starts_with("# frozen_string_literal: true\n"), "got:\n{out}");
    assert!(out.contains("require_relative \"../lib/my_lib\"\n"), "got:\n{out}");
    assert!(out.contains("RSpec.describe MyLib do\n"), "got:\n{out}");
    assert!(
        out.contains("    expect(described_class.ping).to(be(true).or(be(false)))\n"),
        "got:\n{out}"
    );
}

/// The matcher must follow the Magnus type map, not a generic truthiness check.
#[test]
fn matches_the_returned_ruby_type_for_each_return_kind() {
    let cases = [
        (TypeRef::String, "expect(described_class.probe).to(be_a(String))"),
        (
            TypeRef::Primitive(PrimitiveType::U64),
            "expect(described_class.probe).to(be_a(Integer))",
        ),
        (
            TypeRef::Primitive(PrimitiveType::F64),
            "expect(described_class.probe).to(be_a(Float))",
        ),
    ];
    for (return_type, expected) in cases {
        let api = ApiSurface {
            functions: vec![zero_arg_function("probe", return_type)],
            ..Default::default()
        };
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");
        assert!(out.contains(expected), "expected `{expected}`, got:\n{out}");
    }
}

/// A function taking parameters cannot be called generically (unknown ownership and
/// conversion needs per parameter), so the ladder must degrade instead of guessing.
#[test]
fn skips_functions_that_take_parameters() {
    let api = ApiSurface {
        functions: vec![FunctionDef {
            params: vec![crate::core::ir::ParamDef {
                name: "input".to_string(),
                ty: TypeRef::String,
                ..Default::default()
            }],
            ..zero_arg_function("greet", TypeRef::String)
        }],
        types: vec![dto("Widget", vec![simple_field("label", TypeRef::String)])],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(!out.contains("greet"), "got:\n{out}");
    assert!(
        out.contains("described_class::Widget.new(label: \"alef-scaffold\")"),
        "got:\n{out}"
    );
}

/// Async functions run through a Tokio runtime under a differently-named Rust body; the
/// seed must not be the first thing to exercise that path.
#[test]
fn skips_async_functions() {
    let api = ApiSurface {
        functions: vec![FunctionDef {
            is_async: true,
            ..zero_arg_function("fetch", TypeRef::String)
        }],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(!out.contains("fetch"), "got:\n{out}");
    assert!(out.contains("described_class::VERSION"), "got:\n{out}");
}

/// A `cfg`-gated function is registered only when the extension was compiled with that
/// feature, which a scaffold-time seed cannot know.
#[test]
fn skips_cfg_gated_functions() {
    let api = ApiSurface {
        functions: vec![FunctionDef {
            cfg: Some("feature = \"extra\"".to_string()),
            ..zero_arg_function("extra_ping", TypeRef::String)
        }],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(!out.contains("extra_ping"), "got:\n{out}");
}

/// A function the Magnus wrapper generator cannot delegate gets an `unimplemented` body
/// that raises `RuntimeError` when called. It is still registered and callable, so only
/// this predicate keeps the seed off it — otherwise the example would be permanently red
/// on a healthy build.
#[test]
fn skips_functions_whose_generated_body_only_raises() {
    let api = ApiSurface {
        functions: vec![FunctionDef {
            sanitized: true,
            error_type: Some("Error".to_string()),
            ..zero_arg_function("not_delegatable", TypeRef::String)
        }],
        types: vec![dto("Widget", vec![simple_field("label", TypeRef::String)])],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(!out.contains("not_delegatable"), "got:\n{out}");
    assert!(
        out.contains("described_class::Widget.new(label: \"alef-scaffold\")"),
        "got:\n{out}"
    );
}

/// A fallible function can raise for reasons that have nothing to do with the binding, so
/// an infallible candidate wins even when it appears later in the surface.
#[test]
fn prefers_an_infallible_function_over_a_fallible_one() {
    let api = ApiSurface {
        functions: vec![
            FunctionDef {
                error_type: Some("Error".to_string()),
                ..zero_arg_function("might_fail", TypeRef::String)
            },
            zero_arg_function("always_works", TypeRef::String),
        ],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(
        out.contains("    expect(described_class.always_works).to(be_a(String))\n"),
        "got:\n{out}"
    );
    assert!(!out.contains("might_fail"), "got:\n{out}");
}

/// When every candidate is fallible the strongest tier still fires: an example that can
/// fail for a real reason is worth more than degrading to a weaker one.
#[test]
fn still_calls_a_fallible_function_when_it_is_the_only_candidate() {
    let api = ApiSurface {
        functions: vec![FunctionDef {
            error_type: Some("Error".to_string()),
            ..zero_arg_function("might_fail", TypeRef::String)
        }],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(
        out.contains("    expect(described_class.might_fail).to(be_a(String))\n"),
        "got:\n{out}"
    );
}

/// `binding_excluded` functions never reach the generated extension, so the seed must not
/// call one.
#[test]
fn skips_binding_excluded_functions() {
    let api = ApiSurface {
        functions: vec![
            FunctionDef {
                binding_excluded: true,
                ..zero_arg_function("hidden", TypeRef::String)
            },
            zero_arg_function("visible", TypeRef::String),
        ],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(out.contains("described_class.visible"), "got:\n{out}");
    assert!(!out.contains("hidden"), "got:\n{out}");
}

/// `[crates.ruby] exclude_functions` mirrors `MagnusBackend`'s own filter, so a function
/// excluded there must be skipped here too.
#[test]
fn skips_functions_excluded_via_ruby_config() {
    let config = resolve_config(
        r#"
[workspace]
languages = ["ruby"]
[[crates]]
name = "my-lib"
sources = []

[crates.ruby]
exclude_functions = ["ping"]
"#,
    );
    let api = ApiSurface {
        functions: vec![zero_arg_function("ping", TypeRef::String)],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &config, "my_lib");

    assert!(
        !out.contains("ping"),
        "excluded function must not be referenced, got:\n{out}"
    );
    assert!(out.contains("described_class::VERSION"), "got:\n{out}");
}

/// With no callable function, a literal-constructible DTO is built through the generated
/// keyword constructor and every field read back through its accessor.
#[test]
fn constructs_a_simple_dto_and_asserts_every_field() {
    let api = ApiSurface {
        types: vec![dto(
            "Widget",
            vec![
                simple_field("label", TypeRef::String),
                simple_field("count", TypeRef::Primitive(PrimitiveType::U32)),
            ],
        )],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(
        out.contains("    instance = described_class::Widget.new(label: \"alef-scaffold\", count: 1)\n"),
        "got:\n{out}"
    );
    assert!(
        out.contains("    expect([instance.label, instance.count]).to(eq([\"alef-scaffold\", 1]))\n"),
        "got:\n{out}"
    );
}

/// An all-String multi-field DTO must not emit a bracketed `["alef-scaffold",
/// "alef-scaffold"]` array literal: `RUBY_SEED_STRING_LITERAL` is a hyphenated word, which
/// the `.rubocop.yml` scaffolded alongside this file still matches via `Style/WordArray`'s
/// `WordRegex` (it explicitly allows one hyphen) at its default `MinSize` of 2 -- flagging
/// every new Ruby consumer's freshly-scaffolded spec red before a single line is hand-edited.
#[test]
fn constructs_an_all_string_dto_without_a_bracketed_word_array() {
    let api = ApiSurface {
        types: vec![dto(
            "Widget",
            vec![
                simple_field("label", TypeRef::String),
                simple_field("note", TypeRef::String),
            ],
        )],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(
        out.contains("    expect([instance.label, instance.note]).to(eq(%w[alef-scaffold alef-scaffold]))\n"),
        "got:\n{out}"
    );
    assert!(
        !out.contains("[\"alef-scaffold\", \"alef-scaffold\"]"),
        "must not emit a bracketed all-String literal array: got:\n{out}"
    );
}

/// A single-field DTO reads better as a scalar comparison than a one-element array.
#[test]
fn asserts_a_single_field_dto_without_an_array() {
    let api = ApiSurface {
        types: vec![dto("Widget", vec![simple_field("label", TypeRef::String)])],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(
        out.contains("    expect(instance.label).to(eq(\"alef-scaffold\"))\n"),
        "got:\n{out}"
    );
}

/// A `Named` field has no default in the generated constructor, so a partial construction
/// would raise `ArgumentError`. The whole type is rejected rather than partly built.
#[test]
fn falls_back_to_a_constant_reference_for_a_dto_with_a_named_field() {
    let api = ApiSurface {
        types: vec![dto(
            "Widget",
            vec![
                simple_field("label", TypeRef::String),
                simple_field("nested", TypeRef::Named("Other".to_string())),
            ],
        )],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(!out.contains(".new("), "got:\n{out}");
    assert!(
        out.contains("    expect(described_class.const_get(:Widget)).to(be_a(Module))\n"),
        "got:\n{out}"
    );
}

/// Optional fields carry `nil` semantics this seed does not model, so they disqualify the
/// construction tier rather than being guessed at.
#[test]
fn falls_back_to_a_constant_reference_for_a_dto_with_an_optional_field() {
    let api = ApiSurface {
        types: vec![dto(
            "Widget",
            vec![FieldDef {
                optional: true,
                ..simple_field("label", TypeRef::String)
            }],
        )],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(!out.contains(".new("), "got:\n{out}");
    assert!(out.contains("const_get(:Widget)"), "got:\n{out}");
}

/// `[crates.ruby] exclude_types` and `binding_excluded` both remove a class from the
/// generated extension, so neither may be named by the seed.
#[test]
fn skips_types_excluded_by_config_or_binding_exclusion() {
    let config = resolve_config(
        r#"
[workspace]
languages = ["ruby"]
[[crates]]
name = "my-lib"
sources = []

[crates.ruby]
exclude_types = ["Excluded"]
"#,
    );
    let api = ApiSurface {
        types: vec![
            dto("Excluded", vec![simple_field("label", TypeRef::String)]),
            TypeDef {
                binding_excluded: true,
                ..dto("Hidden", vec![simple_field("label", TypeRef::String)])
            },
            dto("Visible", vec![simple_field("label", TypeRef::String)]),
        ],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &config, "my_lib");

    assert!(!out.contains("Excluded"), "got:\n{out}");
    assert!(!out.contains("Hidden"), "got:\n{out}");
    assert!(out.contains("described_class::Visible.new("), "got:\n{out}");
}

/// `MagnusBackend::generate_public_api` drops `*Update` and `*Builder` types from the
/// module's curated re-export list, so a seed naming one may reference nothing.
#[test]
fn skips_update_and_builder_types() {
    let api = ApiSurface {
        types: vec![
            dto("WidgetUpdate", vec![simple_field("label", TypeRef::String)]),
            dto("WidgetBuilder", vec![simple_field("label", TypeRef::String)]),
        ],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(!out.contains("WidgetUpdate"), "got:\n{out}");
    assert!(!out.contains("WidgetBuilder"), "got:\n{out}");
    assert!(out.contains("described_class::VERSION"), "got:\n{out}");
}

/// Enums are not registered as Ruby constants by the Magnus backend, so an enum-only
/// surface must degrade to the version tier rather than name a constant that is absent.
#[test]
fn never_names_an_enum_because_magnus_registers_none_as_constants() {
    let api = ApiSurface {
        enums: vec![crate::core::ir::EnumDef {
            name: "Colour".to_string(),
            ..Default::default()
        }],
        ..Default::default()
    };
    let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");

    assert!(!out.contains("Colour"), "got:\n{out}");
    assert!(out.contains("described_class::VERSION"), "got:\n{out}");
}

/// An empty API surface still gets a falsifiable example: `VERSION` only resolves once the
/// gem — and therefore the native extension `native.rb` dlopens — has loaded.
#[test]
fn falls_back_to_the_version_assertion_when_the_api_surface_is_empty() {
    let out = scaffold_ruby_spec(&ApiSurface::default(), &minimal_config(), "my_lib");

    assert!(
        out.contains("    expect(described_class::VERSION).to match(/\\A\\d+\\.\\d+\\.\\d+/)\n"),
        "got:\n{out}"
    );
}

/// No tier may emit a tautology, and every tier must go through the `require_relative`
/// that dlopens the native extension — that is the property making even the weakest tier
/// falsifiable rather than decorative.
#[test]
fn no_tier_emits_a_vacuous_or_unlinked_example() {
    let surfaces = [
        ApiSurface {
            functions: vec![zero_arg_function("ping", TypeRef::String)],
            ..Default::default()
        },
        ApiSurface {
            types: vec![dto("Widget", vec![simple_field("label", TypeRef::String)])],
            ..Default::default()
        },
        ApiSurface {
            types: vec![dto(
                "Widget",
                vec![simple_field("nested", TypeRef::Named("Other".to_string()))],
            )],
            ..Default::default()
        },
        ApiSurface::default(),
    ];
    for api in surfaces {
        let out = scaffold_ruby_spec(&api, &minimal_config(), "my_lib");
        assert!(
            out.contains("require_relative \"../lib/my_lib\""),
            "every tier must load the gem, got:\n{out}"
        );
        assert_eq!(out.matches("  it \"").count(), 1, "exactly one example, got:\n{out}");
        for tautology in ["expect(1)", "eq(1 + 1)", "to be_truthy", "to be_falsey"] {
            assert!(!out.contains(tautology), "vacuous assertion `{tautology}` in:\n{out}");
        }
        assert!(
            out.contains("described_class"),
            "the example must assert against the generated module, got:\n{out}"
        );
    }
}

/// The seed carries no alef header marker, and must not: the marker is what
/// `write_scaffold_files_report`'s ownership guard reads as "alef owns this file", which
/// would let an `overwrite: true` run (e.g. `alef version`) replace a hand-written suite.
#[test]
fn seed_content_carries_no_alef_marker() {
    let out = scaffold_ruby_spec(&ApiSurface::default(), &minimal_config(), "my_lib");

    assert!(
        !crate::core::hash::content_has_alef_marker(&out),
        "seed must stay unmarked so it is never reclaimed by an overwrite run, got:\n{out}"
    );
}

/// The seed lands at the path the generated `Rakefile`'s `RSpec::Core::RakeTask` already
/// scans, and is emitted create-only so a real suite is never overwritten.
#[test]
fn seed_is_emitted_create_only_at_the_rspec_default_path() {
    let config = minimal_config();
    let api = ApiSurface {
        version: "1.2.3".to_string(),
        ..Default::default()
    };
    let files = scaffold_ruby(&api, &config).expect("scaffold");
    let spec = files
        .iter()
        .find(|f| f.path.to_string_lossy().contains("/spec/"))
        .expect("a spec seed must be emitted");

    assert_eq!(spec.path.to_string_lossy(), "packages/ruby/spec/my_lib_spec.rb");
    assert!(!spec.generated_header, "the seed must stay create-only");
}

/// The `~keep` in this seed's rationale is load-bearing, unlike the markers the
/// render-time strip (`core::keep_marker`) removes from `.jinja` output. The seed is
/// create-only, so alef never rewrites it and the consumer's own `poly` uncomment pass is
/// what reads it — without the marker the rationale is deleted by the next `poly fmt`.
/// Pinned across every tier so a broadening of the strip cannot silently take it. ~keep
#[test]
fn every_seed_tier_keeps_its_uncomment_pass_marker() {
    let config = minimal_config();
    let tiers = [
        (
            "call",
            ApiSurface {
                functions: vec![zero_arg_function("ping", TypeRef::Primitive(PrimitiveType::Bool))],
                ..Default::default()
            },
        ),
        (
            "construct",
            ApiSurface {
                types: vec![dto("Widget", vec![simple_field("label", TypeRef::String)])],
                ..Default::default()
            },
        ),
        (
            "constant",
            ApiSurface {
                types: vec![dto(
                    "Widget",
                    vec![
                        simple_field("label", TypeRef::String),
                        simple_field("nested", TypeRef::Named("Other".to_string())),
                    ],
                )],
                ..Default::default()
            },
        ),
        ("version", ApiSurface::default()),
    ];

    for (tier, api) in tiers {
        let out = scaffold_ruby_spec(&api, &config, "my_lib");
        assert!(
            out.contains("replace it with a real suite. ~keep") || out.contains("break on the next release. ~keep"),
            "the {tier} tier lost its uncomment-pass marker, got:\n{out}"
        );
    }
}

/// Regression for the gemspec/RuboCop deadlock: alef's generated `.gemspec` once filtered
/// `spec.files` with `.reject { |f| f.match?(%r{...}) }`, which RuboCop's
/// `Style/SelectByRegexp` flags (it wants `grep_v`). Both the gemspec and the `.rubocop.yml`
/// that lints it are `generated_header: true`, so the consumer has no file they can hand-edit
/// to escape the violation -- `alef build` reintroduces it every run. This test does not shell
/// out to `rubocop` (not guaranteed present in CI); instead it structurally forbids the exact
/// shape the cop flags -- a `.select`/`.reject` block whose predicate is `<expr>.match?(%r{...})`
/// -- anywhere in the generated gemspec, and confirms `grep_v` is present as the replacement.
#[test]
fn gemspec_files_filter_never_reintroduces_the_select_by_regexp_anti_pattern() {
    let files = scaffold_ruby(&ApiSurface::default(), &minimal_config()).expect("scaffold");
    let gemspec = files
        .iter()
        .find(|f| f.path.to_string_lossy().ends_with(".gemspec"))
        .expect("a gemspec must be emitted");

    let select_by_regexp_shape = regex_lite_contains_match_predicate(&gemspec.content);
    assert!(
        !select_by_regexp_shape,
        "gemspec re-introduces the Style/SelectByRegexp anti-pattern \
         (`.select`/`.reject` with a `.match?(%r{{...}})` predicate), got:\n{}",
        gemspec.content
    );
    assert!(
        gemspec.content.contains(".grep_v(%r{"),
        "gemspec must filter spec.files via grep_v, RuboCop's own autocorrect target, got:\n{}",
        gemspec.content
    );
}

/// Scans for `.select { |x| <expr>.match?(%r{...}) }` or `.reject { |x| <expr>.match?(%r{...}) }`
/// without pulling in a full regex engine dependency for one test: a hand-rolled scanner over
/// the small, fixed set of generated files is enough to catch the specific shape RuboCop's
/// `Style/SelectByRegexp` flags.
fn regex_lite_contains_match_predicate(content: &str) -> bool {
    for method in [".select {", ".reject {", ".select{", ".reject{"] {
        let mut search_from = 0;
        while let Some(offset) = content[search_from..].find(method) {
            let start = search_from + offset;
            let block_end = content[start..].find('}').map_or(content.len(), |end| start + end + 1);
            if content[start..block_end].contains(".match?(%r{") {
                return true;
            }
            search_from = start + method.len();
        }
    }
    false
}

/// Defense in depth: even after the `Style/SelectByRegexp` fix, a *future* RuboCop cop could
/// flag something else in the alef-owned gemspec or Rakefile, and the consumer would again have
/// no file to hand-edit around it (both carry `generated_header: true`, so `alef build`
/// overwrites any workaround). Excluding both from `AllCops.Exclude` in the generated
/// `.rubocop.yml` -- mirroring the Go backend's `exclusions: generated: lax` -- means a new cop
/// can no longer reopen this exact deadlock shape on a file the consumer cannot edit.
#[test]
fn rubocop_config_excludes_the_alef_owned_gemspec_and_rakefile() {
    let files = scaffold_ruby(&ApiSurface::default(), &minimal_config()).expect("scaffold");
    let rubocop_yml = files
        .iter()
        .find(|f| f.path.to_string_lossy().ends_with(".rubocop.yml"))
        .expect("a .rubocop.yml must be emitted");

    assert!(
        rubocop_yml.content.contains("\"*.gemspec\""),
        "AllCops.Exclude must cover the alef-owned gemspec, got:\n{}",
        rubocop_yml.content
    );
    assert!(
        rubocop_yml.content.contains("\"Rakefile\""),
        "AllCops.Exclude must cover the alef-owned Rakefile, got:\n{}",
        rubocop_yml.content
    );
}