Skip to main content

alef_e2e/codegen/
ruby.rs

1//! Ruby e2e test generator using RSpec.
2//!
3//! Generates `e2e/ruby/Gemfile` and `spec/{category}_spec.rb` files from
4//! JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.
5
6use crate::config::E2eConfig;
7use crate::escape::{ruby_string_literal, sanitize_filename, sanitize_ident};
8use crate::field_access::FieldResolver;
9use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup};
10use alef_core::backend::GeneratedFile;
11use alef_core::config::AlefConfig;
12use anyhow::Result;
13use heck::ToSnakeCase;
14use std::collections::HashMap;
15use std::fmt::Write as FmtWrite;
16use std::path::PathBuf;
17
18use super::E2eCodegen;
19
20/// Ruby e2e code generator.
21pub struct RubyCodegen;
22
23impl E2eCodegen for RubyCodegen {
24    fn generate(
25        &self,
26        groups: &[FixtureGroup],
27        e2e_config: &E2eConfig,
28        alef_config: &AlefConfig,
29    ) -> Result<Vec<GeneratedFile>> {
30        let lang = self.language_name();
31        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
32
33        let mut files = Vec::new();
34
35        // Resolve call config with overrides.
36        let call = &e2e_config.call;
37        let overrides = call.overrides.get(lang);
38        let module_path = overrides
39            .and_then(|o| o.module.as_ref())
40            .cloned()
41            .unwrap_or_else(|| call.module.clone());
42        let function_name = overrides
43            .and_then(|o| o.function.as_ref())
44            .cloned()
45            .unwrap_or_else(|| call.function.clone());
46        let class_name = overrides.and_then(|o| o.class.as_ref()).cloned();
47        let options_type = overrides.and_then(|o| o.options_type.clone());
48        let empty_enum_fields = HashMap::new();
49        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
50        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
51        let result_var = &call.result_var;
52
53        // Resolve package config.
54        let ruby_pkg = e2e_config.resolve_package("ruby");
55        let gem_name = ruby_pkg
56            .as_ref()
57            .and_then(|p| p.name.as_ref())
58            .cloned()
59            .unwrap_or_else(|| alef_config.crate_config.name.replace('-', "_"));
60        let gem_path = ruby_pkg
61            .as_ref()
62            .and_then(|p| p.path.as_ref())
63            .cloned()
64            .unwrap_or_else(|| "../../packages/ruby".to_string());
65        let gem_version = ruby_pkg
66            .as_ref()
67            .and_then(|p| p.version.as_ref())
68            .cloned()
69            .unwrap_or_else(|| "0.1.0".to_string());
70
71        // Generate Gemfile.
72        files.push(GeneratedFile {
73            path: output_base.join("Gemfile"),
74            content: render_gemfile(&gem_name, &gem_path, &gem_version, e2e_config.dep_mode),
75            generated_header: false,
76        });
77
78        // Generate .rubocop.yaml for linting generated specs.
79        files.push(GeneratedFile {
80            path: output_base.join(".rubocop.yaml"),
81            content: render_rubocop_yaml(),
82            generated_header: false,
83        });
84
85        // Generate spec files per category.
86        let spec_base = output_base.join("spec");
87
88        for group in groups {
89            let active: Vec<&Fixture> = group
90                .fixtures
91                .iter()
92                .filter(|f| f.skip.as_ref().is_none_or(|s| !s.should_skip(lang)))
93                .collect();
94
95            if active.is_empty() {
96                continue;
97            }
98
99            let field_resolver_pre = FieldResolver::new(
100                &e2e_config.fields,
101                &e2e_config.fields_optional,
102                &e2e_config.result_fields,
103                &e2e_config.fields_array,
104            );
105            // Skip the entire file if no fixture in this category produces output.
106            let has_any_output = active.iter().any(|f| {
107                let expects_error = f.assertions.iter().any(|a| a.assertion_type == "error");
108                expects_error || has_usable_assertion(f, &field_resolver_pre, result_is_simple)
109            });
110            if !has_any_output {
111                continue;
112            }
113
114            let filename = format!("{}_spec.rb", sanitize_filename(&group.category));
115            let field_resolver = FieldResolver::new(
116                &e2e_config.fields,
117                &e2e_config.fields_optional,
118                &e2e_config.result_fields,
119                &e2e_config.fields_array,
120            );
121            let content = render_spec_file(
122                &group.category,
123                &active,
124                &module_path,
125                &function_name,
126                class_name.as_deref(),
127                result_var,
128                &gem_name,
129                &e2e_config.call.args,
130                &field_resolver,
131                options_type.as_deref(),
132                enum_fields,
133                result_is_simple,
134            );
135            files.push(GeneratedFile {
136                path: spec_base.join(filename),
137                content,
138                generated_header: true,
139            });
140        }
141
142        Ok(files)
143    }
144
145    fn language_name(&self) -> &'static str {
146        "ruby"
147    }
148}
149
150// ---------------------------------------------------------------------------
151// Rendering
152// ---------------------------------------------------------------------------
153
154fn render_gemfile(
155    gem_name: &str,
156    gem_path: &str,
157    gem_version: &str,
158    dep_mode: crate::config::DependencyMode,
159) -> String {
160    let gem_line = match dep_mode {
161        crate::config::DependencyMode::Registry => format!("gem '{gem_name}', '{gem_version}'"),
162        crate::config::DependencyMode::Local => format!("gem '{gem_name}', path: '{gem_path}'"),
163    };
164    format!(
165        "# frozen_string_literal: true\n\
166         \n\
167         source 'https://rubygems.org'\n\
168         \n\
169         {gem_line}\n\
170         gem 'rspec', '~> 3.13'\n\
171         gem 'rubocop', '~> 1.86'\n\
172         gem 'rubocop-rspec', '~> 3.9'\n"
173    )
174}
175
176fn render_rubocop_yaml() -> String {
177    r#"# Generated by alef e2e — do not edit.
178AllCops:
179  NewCops: enable
180  TargetRubyVersion: 3.2
181  SuggestExtensions: false
182
183plugins:
184  - rubocop-rspec
185
186# --- Justified suppressions for generated test code ---
187
188# Generated tests are verbose by nature (setup + multiple assertions).
189Metrics/BlockLength:
190  Enabled: false
191Metrics/MethodLength:
192  Enabled: false
193Layout/LineLength:
194  Enabled: false
195
196# Generated tests use multiple assertions per example for thorough verification.
197RSpec/MultipleExpectations:
198  Enabled: false
199RSpec/ExampleLength:
200  Enabled: false
201
202# Generated tests describe categories as strings, not classes.
203RSpec/DescribeClass:
204  Enabled: false
205
206# Fixture-driven tests may produce identical assertion bodies for different inputs.
207RSpec/RepeatedExample:
208  Enabled: false
209
210# Error-handling tests use bare raise_error (exception type not known at generation time).
211RSpec/UnspecifiedException:
212  Enabled: false
213"#
214    .to_string()
215}
216
217#[allow(clippy::too_many_arguments)]
218fn render_spec_file(
219    category: &str,
220    fixtures: &[&Fixture],
221    module_path: &str,
222    function_name: &str,
223    class_name: Option<&str>,
224    result_var: &str,
225    gem_name: &str,
226    args: &[crate::config::ArgMapping],
227    field_resolver: &FieldResolver,
228    options_type: Option<&str>,
229    enum_fields: &HashMap<String, String>,
230    result_is_simple: bool,
231) -> String {
232    let mut out = String::new();
233    let _ = writeln!(out, "# This file is auto-generated by alef. DO NOT EDIT.");
234    let _ = writeln!(out, "# frozen_string_literal: true");
235    let _ = writeln!(out);
236
237    // Require the gem (single quotes).
238    let require_name = if module_path.is_empty() { gem_name } else { module_path };
239    let _ = writeln!(out, "require '{}'", require_name.replace('-', "_"));
240    let _ = writeln!(out, "require 'json'");
241    let _ = writeln!(out);
242
243    // Build the Ruby module/class qualifier for calls.
244    let call_receiver = class_name
245        .map(|s| s.to_string())
246        .unwrap_or_else(|| ruby_module_name(module_path));
247
248    let _ = writeln!(out, "RSpec.describe '{}' do", category);
249
250    let mut first = true;
251    for fixture in fixtures {
252        if !first {
253            let _ = writeln!(out);
254        }
255        first = false;
256
257        render_example(
258            &mut out,
259            fixture,
260            function_name,
261            &call_receiver,
262            result_var,
263            args,
264            field_resolver,
265            options_type,
266            enum_fields,
267            result_is_simple,
268        );
269    }
270
271    let _ = writeln!(out, "end");
272    out
273}
274
275/// Check if a fixture has at least one assertion that will produce an executable
276/// expect() call (not just a skip comment).
277fn has_usable_assertion(fixture: &Fixture, field_resolver: &FieldResolver, result_is_simple: bool) -> bool {
278    fixture.assertions.iter().any(|a| {
279        // not_error is implicit (call succeeding), error is handled separately.
280        if a.assertion_type == "not_error" || a.assertion_type == "error" {
281            return false;
282        }
283        // Check field validity.
284        if let Some(f) = &a.field {
285            if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
286                return false;
287            }
288            // When result_is_simple, skip non-content fields.
289            if result_is_simple {
290                let f_lower = f.to_lowercase();
291                if !f.is_empty()
292                    && f_lower != "content"
293                    && (f_lower.starts_with("metadata")
294                        || f_lower.starts_with("document")
295                        || f_lower.starts_with("structure"))
296                {
297                    return false;
298                }
299            }
300        }
301        true
302    })
303}
304
305#[allow(clippy::too_many_arguments)]
306fn render_example(
307    out: &mut String,
308    fixture: &Fixture,
309    function_name: &str,
310    call_receiver: &str,
311    result_var: &str,
312    args: &[crate::config::ArgMapping],
313    field_resolver: &FieldResolver,
314    options_type: Option<&str>,
315    enum_fields: &HashMap<String, String>,
316    result_is_simple: bool,
317) {
318    let test_name = sanitize_ident(&fixture.id);
319    let description = fixture.description.replace('\'', "\\'");
320    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
321
322    let (mut setup_lines, args_str) = build_args_and_setup(
323        &fixture.input,
324        args,
325        call_receiver,
326        options_type,
327        enum_fields,
328        result_is_simple,
329        &fixture.id,
330    );
331
332    // Build visitor if present and add to setup
333    let mut visitor_arg = String::new();
334    if let Some(visitor_spec) = &fixture.visitor {
335        visitor_arg = build_ruby_visitor(&mut setup_lines, visitor_spec);
336    }
337
338    let final_args = if visitor_arg.is_empty() {
339        args_str
340    } else if args_str.is_empty() {
341        visitor_arg
342    } else {
343        format!("{args_str}, {visitor_arg}")
344    };
345
346    let call_expr = format!("{call_receiver}.{function_name}({final_args})");
347
348    let _ = writeln!(out, "  it '{test_name}: {description}' do");
349
350    for line in &setup_lines {
351        let _ = writeln!(out, "    {line}");
352    }
353
354    if expects_error {
355        let _ = writeln!(out, "    expect {{ {call_expr} }}.to raise_error");
356        let _ = writeln!(out, "  end");
357        return;
358    }
359
360    // Check if any non-error assertion actually uses the result variable.
361    let has_usable = has_usable_assertion(fixture, field_resolver, result_is_simple);
362    let _ = writeln!(out, "    {result_var} = {call_expr}");
363
364    for assertion in &fixture.assertions {
365        render_assertion(out, assertion, result_var, field_resolver, result_is_simple);
366    }
367
368    // When all assertions were skipped (fields unavailable), the example has no
369    // expect() calls, which triggers rubocop's RSpec/NoExpectationExample cop.
370    // Emit a minimal placeholder expectation so rubocop is satisfied.
371    if !has_usable {
372        let _ = writeln!(out, "    expect({result_var}).not_to be_nil");
373    }
374
375    let _ = writeln!(out, "  end");
376}
377
378/// Build setup lines (e.g. handle creation) and the argument list for the function call.
379///
380/// Returns `(setup_lines, args_string)`.
381fn build_args_and_setup(
382    input: &serde_json::Value,
383    args: &[crate::config::ArgMapping],
384    call_receiver: &str,
385    options_type: Option<&str>,
386    enum_fields: &HashMap<String, String>,
387    result_is_simple: bool,
388    fixture_id: &str,
389) -> (Vec<String>, String) {
390    if args.is_empty() {
391        return (Vec::new(), json_to_ruby(input));
392    }
393
394    let mut setup_lines: Vec<String> = Vec::new();
395    let mut parts: Vec<String> = Vec::new();
396
397    for arg in args {
398        if arg.arg_type == "mock_url" {
399            setup_lines.push(format!(
400                "{} = \"#{{ENV.fetch('MOCK_SERVER_URL')}}/fixtures/{fixture_id}\"",
401                arg.name,
402            ));
403            parts.push(arg.name.clone());
404            continue;
405        }
406
407        if arg.arg_type == "handle" {
408            // Generate a create_engine (or equivalent) call and pass the variable.
409            let constructor_name = format!("create_{}", arg.name.to_snake_case());
410            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
411            let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
412            if config_value.is_null()
413                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
414            {
415                setup_lines.push(format!("{} = {call_receiver}.{constructor_name}(nil)", arg.name,));
416            } else {
417                let literal = json_to_ruby(config_value);
418                let name = &arg.name;
419                setup_lines.push(format!("{name}_config = {literal}"));
420                setup_lines.push(format!(
421                    "{} = {call_receiver}.{constructor_name}({name}_config.to_json)",
422                    arg.name,
423                    name = name,
424                ));
425            }
426            parts.push(arg.name.clone());
427            continue;
428        }
429
430        let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
431        let val = input.get(field);
432        match val {
433            None | Some(serde_json::Value::Null) if arg.optional => {
434                // Optional arg with no fixture value: skip entirely.
435                continue;
436            }
437            None | Some(serde_json::Value::Null) => {
438                // Required arg with no fixture value: pass a language-appropriate default.
439                let default_val = match arg.arg_type.as_str() {
440                    "string" => "''".to_string(),
441                    "int" | "integer" => "0".to_string(),
442                    "float" | "number" => "0.0".to_string(),
443                    "bool" | "boolean" => "false".to_string(),
444                    _ => "nil".to_string(),
445                };
446                parts.push(default_val);
447            }
448            Some(v) => {
449                // For json_object args with options_type, construct a typed options object.
450                // When result_is_simple, the binding accepts a plain Hash (no wrapper class).
451                if arg.arg_type == "json_object" && !v.is_null() {
452                    if let (Some(opts_type), Some(obj)) = (options_type, v.as_object()) {
453                        let kwargs: Vec<String> = obj
454                            .iter()
455                            .map(|(k, vv)| {
456                                let snake_key = k.to_snake_case();
457                                let rb_val = if enum_fields.contains_key(k) {
458                                    if let Some(s) = vv.as_str() {
459                                        let snake_val = s.to_snake_case();
460                                        format!("'{snake_val}'")
461                                    } else {
462                                        json_to_ruby(vv)
463                                    }
464                                } else {
465                                    json_to_ruby(vv)
466                                };
467                                format!("{snake_key}: {rb_val}")
468                            })
469                            .collect();
470                        if result_is_simple {
471                            parts.push(format!("{{{}}}", kwargs.join(", ")));
472                        } else {
473                            parts.push(format!("{opts_type}.new({})", kwargs.join(", ")));
474                        }
475                        continue;
476                    }
477                }
478                parts.push(json_to_ruby(v));
479            }
480        }
481    }
482
483    (setup_lines, parts.join(", "))
484}
485
486fn render_assertion(
487    out: &mut String,
488    assertion: &Assertion,
489    result_var: &str,
490    field_resolver: &FieldResolver,
491    result_is_simple: bool,
492) {
493    // Skip assertions on fields that don't exist on the result type.
494    if let Some(f) = &assertion.field {
495        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
496            let _ = writeln!(out, "    # skipped: field '{f}' not available on result type");
497            return;
498        }
499    }
500
501    // When result_is_simple, skip assertions that reference non-content fields.
502    if result_is_simple {
503        if let Some(f) = &assertion.field {
504            let f_lower = f.to_lowercase();
505            if !f.is_empty()
506                && f_lower != "content"
507                && (f_lower.starts_with("metadata")
508                    || f_lower.starts_with("document")
509                    || f_lower.starts_with("structure"))
510            {
511                return;
512            }
513        }
514    }
515
516    let field_expr = if result_is_simple {
517        result_var.to_string()
518    } else {
519        match &assertion.field {
520            Some(f) if !f.is_empty() => field_resolver.accessor(f, "ruby", result_var),
521            _ => result_var.to_string(),
522        }
523    };
524
525    // For string equality, strip trailing whitespace to handle trailing newlines
526    // from the converter.
527    let stripped_field_expr = if result_is_simple {
528        format!("{field_expr}.strip")
529    } else {
530        field_expr.clone()
531    };
532
533    match assertion.assertion_type.as_str() {
534        "equals" => {
535            if let Some(expected) = &assertion.value {
536                // Use be(true)/be(false) for booleans (RSpec/BeEq).
537                if let Some(b) = expected.as_bool() {
538                    let _ = writeln!(out, "    expect({stripped_field_expr}).to be({b})");
539                } else {
540                    let rb_val = json_to_ruby(expected);
541                    let _ = writeln!(out, "    expect({stripped_field_expr}).to eq({rb_val})");
542                }
543            }
544        }
545        "contains" => {
546            if let Some(expected) = &assertion.value {
547                let rb_val = json_to_ruby(expected);
548                // Use .to_s to handle both String and Symbol (enum) fields
549                let _ = writeln!(out, "    expect({field_expr}.to_s).to include({rb_val})");
550            }
551        }
552        "contains_all" => {
553            if let Some(values) = &assertion.values {
554                for val in values {
555                    let rb_val = json_to_ruby(val);
556                    let _ = writeln!(out, "    expect({field_expr}.to_s).to include({rb_val})");
557                }
558            }
559        }
560        "not_contains" => {
561            if let Some(expected) = &assertion.value {
562                let rb_val = json_to_ruby(expected);
563                let _ = writeln!(out, "    expect({field_expr}.to_s).not_to include({rb_val})");
564            }
565        }
566        "not_empty" => {
567            let _ = writeln!(out, "    expect({field_expr}).not_to be_empty");
568        }
569        "is_empty" => {
570            // Handle nil (None) as empty for optional fields
571            let _ = writeln!(out, "    expect({field_expr}.nil? || {field_expr}.empty?).to be(true)");
572        }
573        "contains_any" => {
574            if let Some(values) = &assertion.values {
575                let items: Vec<String> = values.iter().map(json_to_ruby).collect();
576                let arr_str = items.join(", ");
577                let _ = writeln!(
578                    out,
579                    "    expect([{arr_str}].any? {{ |v| {field_expr}.to_s.include?(v) }}).to be(true)"
580                );
581            }
582        }
583        "greater_than" => {
584            if let Some(val) = &assertion.value {
585                let rb_val = json_to_ruby(val);
586                let _ = writeln!(out, "    expect({field_expr}).to be > {rb_val}");
587            }
588        }
589        "less_than" => {
590            if let Some(val) = &assertion.value {
591                let rb_val = json_to_ruby(val);
592                let _ = writeln!(out, "    expect({field_expr}).to be < {rb_val}");
593            }
594        }
595        "greater_than_or_equal" => {
596            if let Some(val) = &assertion.value {
597                let rb_val = json_to_ruby(val);
598                let _ = writeln!(out, "    expect({field_expr}).to be >= {rb_val}");
599            }
600        }
601        "less_than_or_equal" => {
602            if let Some(val) = &assertion.value {
603                let rb_val = json_to_ruby(val);
604                let _ = writeln!(out, "    expect({field_expr}).to be <= {rb_val}");
605            }
606        }
607        "starts_with" => {
608            if let Some(expected) = &assertion.value {
609                let rb_val = json_to_ruby(expected);
610                let _ = writeln!(out, "    expect({field_expr}).to start_with({rb_val})");
611            }
612        }
613        "ends_with" => {
614            if let Some(expected) = &assertion.value {
615                let rb_val = json_to_ruby(expected);
616                let _ = writeln!(out, "    expect({field_expr}).to end_with({rb_val})");
617            }
618        }
619        "min_length" => {
620            if let Some(val) = &assertion.value {
621                if let Some(n) = val.as_u64() {
622                    let _ = writeln!(out, "    expect({field_expr}.length).to be >= {n}");
623                }
624            }
625        }
626        "max_length" => {
627            if let Some(val) = &assertion.value {
628                if let Some(n) = val.as_u64() {
629                    let _ = writeln!(out, "    expect({field_expr}.length).to be <= {n}");
630                }
631            }
632        }
633        "count_min" => {
634            if let Some(val) = &assertion.value {
635                if let Some(n) = val.as_u64() {
636                    let _ = writeln!(out, "    expect({field_expr}.length).to be >= {n}");
637                }
638            }
639        }
640        "count_equals" => {
641            if let Some(val) = &assertion.value {
642                if let Some(n) = val.as_u64() {
643                    let _ = writeln!(out, "    expect({field_expr}.length).to eq({n})");
644                }
645            }
646        }
647        "is_true" => {
648            let _ = writeln!(out, "    expect({field_expr}).to be true");
649        }
650        "not_error" => {
651            // Already handled by the call succeeding without exception.
652        }
653        "error" => {
654            // Handled at the example level.
655        }
656        other => {
657            let _ = writeln!(out, "    # TODO: unsupported assertion type: {other}");
658        }
659    }
660}
661
662/// Convert a module path (e.g., "html_to_markdown") to Ruby PascalCase module name
663/// (e.g., "HtmlToMarkdown").
664fn ruby_module_name(module_path: &str) -> String {
665    use heck::ToUpperCamelCase;
666    module_path.to_upper_camel_case()
667}
668
669/// Convert a `serde_json::Value` to a Ruby literal string, preferring single quotes.
670fn json_to_ruby(value: &serde_json::Value) -> String {
671    match value {
672        serde_json::Value::String(s) => ruby_string_literal(s),
673        serde_json::Value::Bool(true) => "true".to_string(),
674        serde_json::Value::Bool(false) => "false".to_string(),
675        serde_json::Value::Number(n) => n.to_string(),
676        serde_json::Value::Null => "nil".to_string(),
677        serde_json::Value::Array(arr) => {
678            let items: Vec<String> = arr.iter().map(json_to_ruby).collect();
679            format!("[{}]", items.join(", "))
680        }
681        serde_json::Value::Object(map) => {
682            let items: Vec<String> = map
683                .iter()
684                .map(|(k, v)| format!("{} => {}", ruby_string_literal(k), json_to_ruby(v)))
685                .collect();
686            format!("{{ {} }}", items.join(", "))
687        }
688    }
689}
690
691// ---------------------------------------------------------------------------
692// Visitor generation
693// ---------------------------------------------------------------------------
694
695/// Build a Ruby visitor object and add setup lines. Returns the visitor expression.
696fn build_ruby_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
697    setup_lines.push("visitor = Class.new do".to_string());
698    for (method_name, action) in &visitor_spec.callbacks {
699        emit_ruby_visitor_method(setup_lines, method_name, action);
700    }
701    setup_lines.push("end.new".to_string());
702    "visitor".to_string()
703}
704
705/// Emit a Ruby visitor method for a callback action.
706fn emit_ruby_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
707    let snake_method = method_name;
708    let params = match method_name {
709        "visit_link" => "ctx, href, text, title",
710        "visit_image" => "ctx, src, alt, title",
711        "visit_heading" => "ctx, level, text, id",
712        "visit_code_block" => "ctx, lang, code",
713        "visit_code_inline"
714        | "visit_strong"
715        | "visit_emphasis"
716        | "visit_strikethrough"
717        | "visit_underline"
718        | "visit_subscript"
719        | "visit_superscript"
720        | "visit_mark"
721        | "visit_button"
722        | "visit_summary"
723        | "visit_figcaption"
724        | "visit_definition_term"
725        | "visit_definition_description" => "ctx, text",
726        "visit_text" => "ctx, text",
727        "visit_list_item" => "ctx, ordered, marker, text",
728        "visit_blockquote" => "ctx, content, depth",
729        "visit_table_row" => "ctx, cells, is_header",
730        "visit_custom_element" => "ctx, tag_name, html",
731        "visit_form" => "ctx, action_url, method",
732        "visit_input" => "ctx, input_type, name, value",
733        "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
734        "visit_details" => "ctx, is_open",
735        _ => "ctx",
736    };
737
738    setup_lines.push(format!("  def {snake_method}({params})"));
739    match action {
740        CallbackAction::Skip => {
741            setup_lines.push("    'skip'".to_string());
742        }
743        CallbackAction::Continue => {
744            setup_lines.push("    'continue'".to_string());
745        }
746        CallbackAction::PreserveHtml => {
747            setup_lines.push("    'preserve_html'".to_string());
748        }
749        CallbackAction::Custom { output } => {
750            let escaped = ruby_string_literal(output);
751            setup_lines.push(format!("    {{ custom: {escaped} }}"));
752        }
753        CallbackAction::CustomTemplate { template } => {
754            setup_lines.push(format!("    {{ custom: \"{template}\" }}"));
755        }
756    }
757    setup_lines.push("  end".to_string());
758}