From 283956605312cd7c757aa739a0154350d78ddac9 Mon Sep 17 00:00:00 2001 From: andreatp Date: Fri, 25 Sep 2026 17:39:32 +0100 Subject: [PATCH 01/25] fix(ruby): autoload namespace barrels so a subclass loads regardless of require order - barrels register their models and enums with autoload instead of requiring them - files require a namespace's barrel, never a model file it registers nor their own barrel - a type no barrel autoloads is required directly, from its own or a parent namespace too - barrels write ::File so a model named File cannot shadow it - remove the unused AddInheritedAndMethodTypesImports - the Ruby IT resolves every registered constant, since a bad registration now fails on first use --- CHANGELOG.md | 1 + it/ruby/spec/integration_test_spec.rb | 14 +++ src/Kiota.Builder/CodeDOM/CodeNamespace.cs | 3 + .../CodeRenderers/CodeRenderer.cs | 3 +- src/Kiota.Builder/Refiners/RubyRefiner.cs | 62 +++++++---- .../Writers/Ruby/CodeNamespaceWriter.cs | 19 +++- .../Writers/Ruby/RubyConventionService.cs | 7 ++ .../Refiners/RubyLanguageRefinerTests.cs | 105 ++++++++++++++++++ .../Writers/Ruby/CodeNamespaceWriterTests.cs | 68 ++++++++++++ 9 files changed, 254 insertions(+), 28 deletions(-) create mode 100644 tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 0891f979f4..cfc8012beb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Preserve models for multipart properties with default content types when other properties specify an encoding. [#7342](https://github.com/microsoft/kiota/issues/7342) - Dart: escape enum options named value or values to avoid conflicts with generated and built-in enum members. [#7807](https://github.com/microsoft/kiota/issues/7807) +- Ruby: namespace barrels register their models and enums with `autoload` instead of requiring them, so a subclass no longer fails to load when its base class file is required first. Other files require the barrel rather than an individual model file, and models now load on first use. [#7956](https://github.com/microsoft/kiota/issues/7956) - C#: escape Unicode line and paragraph separators in generated string literals so generated clients remain valid C# source. - External reference allowlist wildcards no longer cross the URI authority boundary, so a wildcard in the scheme or host cannot match text in the path, the user information or the port. - Initialize inherited Dart model fields in constructor initializer lists. diff --git a/it/ruby/spec/integration_test_spec.rb b/it/ruby/spec/integration_test_spec.rb index 4828948cd9..18668d30ba 100644 --- a/it/ruby/spec/integration_test_spec.rb +++ b/it/ruby/spec/integration_test_spec.rb @@ -11,4 +11,18 @@ api = Integration_test::Client::ApiClient.new(MicrosoftKiotaFaraday::FaradayRequestAdapter.new(auth_provider)) expect(api).to_not be nil end + + # models are autoloaded, so a bad registration only fails when the constant is first used + it "resolves every constant the client registers" do + visit = lambda do |mod, seen| + next if seen.key?(mod) + + seen[mod] = true + mod.constants(false).each do |name| + value = mod.const_get(name, false) + visit.call(value, seen) if value.instance_of?(Module) + end + end + expect { visit.call(Integration_test::Client, {}) }.not_to raise_error + end end diff --git a/src/Kiota.Builder/CodeDOM/CodeNamespace.cs b/src/Kiota.Builder/CodeDOM/CodeNamespace.cs index 846fc67ed8..3e1b364d1a 100644 --- a/src/Kiota.Builder/CodeDOM/CodeNamespace.cs +++ b/src/Kiota.Builder/CodeDOM/CodeNamespace.cs @@ -44,6 +44,9 @@ public CodeFile TryAddCodeFile(string fileName, params CodeElement[] children) return file; } + // such a class takes the file the namespace's barrel would be written to + public bool HasClassNamedAfterItself() => + !string.IsNullOrEmpty(Name) && FindChildByName(Name.Split('.')[^1], false) is not null; public bool IsParentOf(CodeNamespace childNamespace) { ArgumentNullException.ThrowIfNull(childNamespace); diff --git a/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs b/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs index 5382fc37d7..4636ad27e6 100644 --- a/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs +++ b/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs @@ -94,8 +94,7 @@ public virtual bool ShouldRenderNamespaceFile(CodeNamespace codeNamespace) { if (codeNamespace is null) return false; // if the module already has a class with the same name, it's going to be declared automatically - var namespaceNameLastSegment = codeNamespace.Name.Split('.')[^1]; - return Configuration.ShouldWriteBarrelsIfClassExists || codeNamespace.FindChildByName(namespaceNameLastSegment, false) == null; + return Configuration.ShouldWriteBarrelsIfClassExists || !codeNamespace.HasClassNamedAfterItself(); } public static CodeRenderer GetCodeRender(GenerationConfiguration config) diff --git a/src/Kiota.Builder/Refiners/RubyRefiner.cs b/src/Kiota.Builder/Refiners/RubyRefiner.cs index 197766b3ea..361c077a41 100644 --- a/src/Kiota.Builder/Refiners/RubyRefiner.cs +++ b/src/Kiota.Builder/Refiners/RubyRefiner.cs @@ -8,6 +8,7 @@ using Kiota.Builder.Configuration; using Kiota.Builder.Extensions; using Kiota.Builder.PathSegmenters; +using Kiota.Builder.Writers.Ruby; namespace Kiota.Builder.Refiners; @@ -58,6 +59,8 @@ public override Task RefineAsync(CodeNamespace generatedCode, CancellationToken if (generatedCode.FindNamespaceByName(_configuration.ModelsNamespaceName) is CodeNamespace modelsNS) FlattenModelsNamespaces(modelsNS, modelsNS); AddPropertiesAndMethodTypesImports(generatedCode, false, false, true); + // a type in the same or a parent namespace is not always reachable through a barrel + AddPropertiesAndMethodTypesImports(generatedCode, true, true, true, static x => x.Where(static y => y.AllTypes.Any(static z => z.TypeDefinition is CodeClass { Kind: CodeClassKind.Model or CodeClassKind.RequestBuilder } or CodeEnum))); RemoveCancellationParameter(generatedCode); cancellationToken.ThrowIfCancellationRequested(); AddParsableImplementsForModelClasses(generatedCode, "MicrosoftKiotaAbstractions::Parsable"); @@ -123,6 +126,7 @@ public override Task RefineAsync(CodeNamespace generatedCode, CancellationToken "ParseNode", addUsings: true ); + RequireBarrelsOfAutoloadedTypes(generatedCode); }, cancellationToken); } private static void ShortenLongNamespaceNames(CodeElement currentElement) @@ -258,45 +262,61 @@ private static void CorrectPropertyType(CodeProperty currentProperty) new (static x => x is CodeProperty prop && prop.IsOfKind(CodePropertyKind.BackingStore), "microsoft_kiota_abstractions", "BackingStore", "BackedModel", "BackingStoreFactorySingleton" ), }; - private static void AddInheritedAndMethodTypesImports(CodeElement currentElement) - { - if (currentElement is CodeClass currentClass && currentClass.IsOfKind(CodeClassKind.Model) - && currentClass.StartBlock.Inherits != null) - { - currentClass.AddUsing(new CodeUsing { Name = currentClass.StartBlock.Inherits.Name, Declaration = currentClass.StartBlock.Inherits }); - } - CrawlTree(currentElement, AddInheritedAndMethodTypesImports); - } private static void AddNamespaceModuleImports(CodeNamespace clientNamespaceParent, CodeElement current) { if (current is CodeClass currentClass) { var module = currentClass.GetImmediateParentOfType(); - AddModules(clientNamespaceParent, module, (usingToAdd) => + // loading its own barrel would register this file for autoload while it is still loading + AddModules(clientNamespaceParent, RubyConventionService.IsAutoloaded(currentClass) ? module.Parent as CodeNamespace : module, (usingToAdd) => { currentClass.AddUsing(usingToAdd); }); } CrawlTree(current, c => AddNamespaceModuleImports(clientNamespaceParent, c)); } - private static void AddModules(CodeNamespace clientNamespaceParent, CodeNamespace module, Action callback) + private static void AddModules(CodeNamespace clientNamespaceParent, CodeNamespace? module, Action callback) { var definition = module; while (definition != clientNamespaceParent && !string.IsNullOrEmpty(definition?.Name)) { - callback(new CodeUsing - { - Name = definition.Name, - Declaration = new CodeType - { - IsExternal = false, - Name = definition.Name, - TypeDefinition = definition, - } - }); + callback(GetNamespaceUsing(definition)); definition = definition.Parent as CodeNamespace; } } + private static CodeUsing GetNamespaceUsing(CodeNamespace codeNamespace) => new() + { + Name = codeNamespace.Name, + Declaration = new CodeType + { + IsExternal = false, + Name = codeNamespace.Name, + TypeDefinition = codeNamespace, + } + }; + // an autoloaded file is only ever loaded through its barrel, so other files require the barrel + private static void RequireBarrelsOfAutoloadedTypes(CodeElement currentElement) + { + if (currentElement is CodeClass { Parent: CodeNamespace currentNamespace } currentClass) + { + var typeUsings = currentClass.Usings + .Where(static x => !x.IsExternal && x.Declaration?.TypeDefinition is CodeElement definition && RubyConventionService.IsAutoloaded(definition)) + .ToArray(); + if (typeUsings.Length != 0) + { + currentClass.StartBlock.RemoveUsings(typeUsings); + var isAutoloaded = RubyConventionService.IsAutoloaded(currentClass); + var barrels = typeUsings.Select(static x => x.Declaration!.TypeDefinition!.GetImmediateParentOfType()) + .Where(x => !(isAutoloaded && x == currentNamespace)) + .Distinct() + .Where(x => !currentClass.Usings.Any(y => y.Declaration?.TypeDefinition == x)) + .Select(GetNamespaceUsing) + .ToArray(); + currentClass.AddUsing(barrels); + } + } + CrawlTree(currentElement, RequireBarrelsOfAutoloadedTypes); + } private static void CorrectImplements(ProprietableBlockDeclaration block) { block.Implements diff --git a/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs index 66a88afb84..2849830cba 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using Kiota.Builder.CodeDOM; using Kiota.Builder.Extensions; @@ -8,7 +9,6 @@ namespace Kiota.Builder.Writers.Ruby; public class CodeNamespaceWriter : BaseElementWriter { - private const string RequireDirective = "require_relative"; private readonly RubyPathSegmenter PathSegmenter; public CodeNamespaceWriter(RubyConventionService conventionService, RubyPathSegmenter pathSegmenter) : base(conventionService) { @@ -19,9 +19,18 @@ public override void WriteCodeElement(CodeNamespace codeElement, LanguageWriter { ArgumentNullException.ThrowIfNull(codeElement); ArgumentNullException.ThrowIfNull(writer); - foreach (var childModel in codeElement.GetChildElements(true).OfType().OrderBy(static x => x.Name, StringComparer.OrdinalIgnoreCase)) - writer.WriteLine($"{RequireDirective} '{PathSegmenter.GetRelativeFileName(codeElement, childModel).ToSnakeCase()}'"); - NamespaceClassNamesProvider.WriteClassesInOrderOfInheritance(codeElement, x => writer.WriteLine($"{RequireDirective} '{PathSegmenter.GetRelativeFileName(codeElement, x).ToSnakeCase()}'")); + // registering instead of requiring lets a class load its base on demand, in any order + var autoloaded = new List(codeElement.GetChildElements(true).OfType() + .Where(RubyConventionService.IsAutoloaded) + .OrderBy(static x => x.Name, StringComparer.OrdinalIgnoreCase)); + NamespaceClassNamesProvider.WriteClassesInOrderOfInheritance(codeElement, x => + { + if (RubyConventionService.IsAutoloaded(x)) autoloaded.Add(x); + }); + if (autoloaded.Count == 0) return; + conventions.WriteNamespaceModules(codeElement, writer); + foreach (var element in autoloaded) + writer.WriteLine($"autoload :{element.Name.ToFirstCharacterUpperCase()}, ::File.expand_path('{PathSegmenter.GetRelativeFileName(codeElement, element).ToSnakeCase()}', __dir__)"); + conventions.WriteNamespaceClosing(codeElement, writer); } - } diff --git a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs index cc66a2011f..1ac31b5bf3 100644 --- a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs +++ b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs @@ -17,6 +17,13 @@ public class RubyConventionService : CommonLanguageConventionService internal string DocCommentStart = "## "; internal string DocCommentEnd = "## "; public override string TempDictionaryVarName => "url_tpl_params"; + // a namespace barrel autoloads these, so their files are only ever loaded through it + internal static bool IsAutoloaded(CodeElement element) => element switch + { + CodeClass codeClass => codeClass.Parent is CodeNamespace ns && !ns.HasClassNamedAfterItself() && codeClass.IsOfKind(CodeClassKind.Model), + CodeEnum codeEnum => codeEnum.Parent is CodeNamespace ns && !ns.HasClassNamedAfterItself() && codeEnum.Options.Any(), + _ => false, + }; internal static string SanitizeRubyDoubleQuoteLiteral(string? value) { if (string.IsNullOrEmpty(value)) return string.Empty; diff --git a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs index a40ebe9a11..8c030637bd 100644 --- a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs +++ b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs @@ -27,6 +27,111 @@ public RubyLanguageRefinerTests() } #region CommonLanguageRefinerTests [Fact] + public async Task DoesNotRequireItsOwnBarrelFromAnAutoloadedModelAsync() + { + var modelsNS = graphNS.AddNamespace($"{graphNS.Name}.models"); + var model = modelsNS.AddClass(new CodeClass { Name = "animal", Kind = CodeClassKind.Model }).First(); + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.DoesNotContain(model.Usings, x => x.Declaration?.TypeDefinition == modelsNS); + Assert.Contains(model.Usings, x => x.Declaration?.TypeDefinition == graphNS); + } + [Fact] + public async Task RequiresTheBarrelOfAModelUsedFromAnotherNamespaceAsync() + { + var modelsNS = graphNS.AddNamespace($"{graphNS.Name}.models"); + var model = modelsNS.AddClass(new CodeClass { Name = "animal", Kind = CodeClassKind.Model }).First(); + var animalsNS = graphNS.AddNamespace($"{graphNS.Name}.animals"); + var requestBuilder = animalsNS.AddClass(new CodeClass { Name = "animalsRequestBuilder", Kind = CodeClassKind.RequestBuilder }).First(); + requestBuilder.AddMethod(new CodeMethod + { + Name = "get", + Kind = CodeMethodKind.RequestExecutor, + ReturnType = new CodeType { Name = "animal", TypeDefinition = model }, + }); + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.DoesNotContain(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == model); + Assert.Contains(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == modelsNS); + Assert.Contains(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == animalsNS); + } + [Fact] + public async Task RequiresTheBarrelOfABaseClassInAnotherNamespaceAsync() + { + var modelsNS = graphNS.AddNamespace($"{graphNS.Name}.models"); + var baseModel = modelsNS.AddClass(new CodeClass { Name = "repository", Kind = CodeClassKind.Model }).First(); + var reposNS = graphNS.AddNamespace($"{graphNS.Name}.repos"); + var derivedModel = reposNS.AddClass(new CodeClass { Name = "reposGetResponse", Kind = CodeClassKind.Model }).First(); + derivedModel.StartBlock.Inherits = new CodeType { Name = "repository", TypeDefinition = baseModel }; + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.DoesNotContain(derivedModel.Usings, x => x.Declaration?.TypeDefinition == baseModel); + Assert.Contains(derivedModel.Usings, x => x.Declaration?.TypeDefinition == modelsNS); + Assert.DoesNotContain(derivedModel.Usings, x => x.Declaration?.TypeDefinition == reposNS); + } + [Fact] + public async Task RequiresTheModelDirectlyWhenItsNamespaceHasNoBarrelAsync() + { + // a class named after its namespace takes the barrel's file, so there is nothing to autoload from + var modelsNS = graphNS.AddNamespace($"{graphNS.Name}.models"); + modelsNS.AddClass(new CodeClass { Name = "models", Kind = CodeClassKind.Model }); + var model = modelsNS.AddClass(new CodeClass { Name = "widget", Kind = CodeClassKind.Model }).First(); + var widgetsNS = graphNS.AddNamespace($"{graphNS.Name}.widgets"); + var requestBuilder = widgetsNS.AddClass(new CodeClass { Name = "widgetsRequestBuilder", Kind = CodeClassKind.RequestBuilder }).First(); + requestBuilder.AddMethod(new CodeMethod + { + Name = "get", + Kind = CodeMethodKind.RequestExecutor, + ReturnType = new CodeType { Name = "widget", TypeDefinition = model }, + }); + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.Contains(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == model); + } + [Fact] + public async Task RequiresAModelNamedAfterItsNamespaceFromTheSameNamespaceAsync() + { + var keysNS = graphNS.AddNamespace($"{graphNS.Name}.keys"); + var model = keysNS.AddClass(new CodeClass { Name = "keys", Kind = CodeClassKind.Model }).First(); + var requestBuilder = keysNS.AddClass(new CodeClass { Name = "keysRequestBuilder", Kind = CodeClassKind.RequestBuilder }).First(); + requestBuilder.AddMethod(new CodeMethod + { + Name = "get", + Kind = CodeMethodKind.RequestExecutor, + ReturnType = new CodeType { Name = "keys", TypeDefinition = model }, + }); + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.Contains(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == model); + } + [Fact] + public async Task RequiresAModelNamedAfterItsNamespaceFromAChildNamespaceAsync() + { + var vlansNS = graphNS.AddNamespace($"{graphNS.Name}.vlans"); + var model = vlansNS.AddClass(new CodeClass { Name = "vlans", Kind = CodeClassKind.Model }).First(); + var itemNS = vlansNS.AddNamespace($"{vlansNS.Name}.item"); + var requestBuilder = itemNS.AddClass(new CodeClass { Name = "vlanItemRequestBuilder", Kind = CodeClassKind.RequestBuilder }).First(); + requestBuilder.AddMethod(new CodeMethod + { + Name = "get", + Kind = CodeMethodKind.RequestExecutor, + ReturnType = new CodeType { Name = "vlans", TypeDefinition = model }, + }); + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.Contains(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == model); + } + [Fact] + public async Task RequiresARequestBuilderFromTheSameNamespaceAsync() + { + // a trailing slash in a path gives a sibling request builder, such as /oauth/token/ + var tokenNS = graphNS.AddNamespace($"{graphNS.Name}.token"); + var emptySegment = tokenNS.AddClass(new CodeClass { Name = "emptyPathSegmentRequestBuilder", Kind = CodeClassKind.RequestBuilder }).First(); + var requestBuilder = tokenNS.AddClass(new CodeClass { Name = "tokenRequestBuilder", Kind = CodeClassKind.RequestBuilder }).First(); + requestBuilder.AddProperty(new CodeProperty + { + Name = "emptyPathSegment", + Kind = CodePropertyKind.RequestBuilder, + Type = new CodeType { Name = "emptyPathSegmentRequestBuilder", TypeDefinition = emptySegment }, + }); + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.Contains(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == emptySegment); + } + [Fact] public async Task DoesNotKeepCancellationParametersInRequestExecutorsAsync() { var model = root.AddClass(new CodeClass diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs new file mode 100644 index 0000000000..de47902a5b --- /dev/null +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using System.Linq; + +using Kiota.Builder.CodeDOM; +using Kiota.Builder.PathSegmenters; +using Kiota.Builder.Writers; +using Kiota.Builder.Writers.Ruby; + +using Xunit; + +namespace Kiota.Builder.Tests.Writers.Ruby; + +public sealed class CodeNamespaceWriterTests : IDisposable +{ + private const string ClientNamespaceName = "graph"; + private readonly StringWriter tw; + private readonly LanguageWriter writer; + private readonly CodeNamespaceWriter codeElementWriter; + private readonly CodeNamespace modelsNamespace; + + public CodeNamespaceWriterTests() + { + codeElementWriter = new CodeNamespaceWriter(new RubyConventionService(), new RubyPathSegmenter(Path.GetTempPath(), ClientNamespaceName)); + writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.Ruby, "./", ClientNamespaceName); + tw = new StringWriter(); + writer.SetTextWriter(tw); + var root = CodeNamespace.InitRootNamespace(); + modelsNamespace = root.AddNamespace($"{ClientNamespaceName}.models"); + } + public void Dispose() + { + tw?.Dispose(); + GC.SuppressFinalize(this); + } + [Fact] + public void RegistersModelsAndEnumsForAutoloadInsteadOfRequiringThem() + { + var baseModel = modelsNamespace.AddClass(new CodeClass { Name = "animal", Kind = CodeClassKind.Model }).First(); + var derivedModel = modelsNamespace.AddClass(new CodeClass { Name = "cat", Kind = CodeClassKind.Model }).First(); + derivedModel.StartBlock.Inherits = new CodeType { Name = "animal", TypeDefinition = baseModel }; + var colorEnum = modelsNamespace.AddEnum(new CodeEnum { Name = "color" }).First(); + colorEnum.AddOption(new CodeEnumOption { Name = "red" }); + codeElementWriter.WriteCodeElement(modelsNamespace, writer); + var result = tw.ToString(); + Assert.DoesNotContain("require", result, StringComparison.Ordinal); + Assert.Contains("module Graph", result, StringComparison.Ordinal); + Assert.Contains("module Models", result, StringComparison.Ordinal); + Assert.Contains("autoload :Animal, ::File.expand_path('animal', __dir__)", result, StringComparison.Ordinal); + Assert.Contains("autoload :Cat, ::File.expand_path('cat', __dir__)", result, StringComparison.Ordinal); + Assert.Contains("autoload :Color, ::File.expand_path('color', __dir__)", result, StringComparison.Ordinal); + } + [Fact] + public void DoesNotRegisterAnEnumWithoutOptions() + { + // the enum writer emits nothing for it, so the constant would never be defined + modelsNamespace.AddEnum(new CodeEnum { Name = "empty" }); + codeElementWriter.WriteCodeElement(modelsNamespace, writer); + Assert.DoesNotContain("empty", tw.ToString(), StringComparison.OrdinalIgnoreCase); + } + [Fact] + public void WritesNothingForANamespaceWithoutModels() + { + modelsNamespace.AddClass(new CodeClass { Name = "usersRequestBuilder", Kind = CodeClassKind.RequestBuilder }); + codeElementWriter.WriteCodeElement(modelsNamespace, writer); + Assert.Empty(tw.ToString()); + } +} From d6a968651cc02023eb9715dc67d0ef09010e088d Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 11:40:09 +0100 Subject: [PATCH 02/25] style(ruby): indent generated code with two spaces --- it/ruby/.rubocop.yml | 3 --- it/ruby/client.rb | 4 ++-- src/Kiota.Builder/Writers/Ruby/RubyWriter.cs | 2 +- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index cfbc284e88..5bbdabd17e 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -17,9 +17,6 @@ Layout/TrailingWhitespace: Layout/FirstHashElementIndentation: Enabled: false -Layout/IndentationWidth: - Enabled: false - Layout/SpaceInsideBlockBraces: Enabled: false diff --git a/it/ruby/client.rb b/it/ruby/client.rb index 3f69625626..87a5aa7bd0 100644 --- a/it/ruby/client.rb +++ b/it/ruby/client.rb @@ -1,6 +1,6 @@ require_relative "api_client" module Integration_test - module Client - end + module Client + end end diff --git a/src/Kiota.Builder/Writers/Ruby/RubyWriter.cs b/src/Kiota.Builder/Writers/Ruby/RubyWriter.cs index aa53280cad..9561fe308b 100644 --- a/src/Kiota.Builder/Writers/Ruby/RubyWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/RubyWriter.cs @@ -4,7 +4,7 @@ namespace Kiota.Builder.Writers.Ruby; public class RubyWriter : LanguageWriter { - public RubyWriter(string rootPath, string clientNamespaceName) + public RubyWriter(string rootPath, string clientNamespaceName) : base(" ", 2) { PathSegmenter = new RubyPathSegmenter(rootPath, clientNamespaceName); var conventionService = new RubyConventionService(); From f02f9d7f8cc11983b5176edd1f39972a08340640 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 11:43:30 +0100 Subject: [PATCH 03/25] style(ruby): write YARD doc comments without trailing whitespace --- it/ruby/.rubocop.yml | 3 --- it/ruby/spec/basic/integration_test_basic.rb | 2 +- .../integration_test_defaultvalues.rb | 16 ++++++++-------- .../Writers/Ruby/CodeMethodWriter.cs | 7 +++---- .../Writers/Ruby/RubyConventionService.cs | 12 +++++------- .../Writers/Ruby/CodeMethodWriterTests.cs | 18 ++++++++++++++++++ 6 files changed, 35 insertions(+), 23 deletions(-) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index 5bbdabd17e..9342e78eec 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -11,9 +11,6 @@ Style/StringLiteralsInInterpolation: Layout/LineLength: Enabled: false -Layout/TrailingWhitespace: - Enabled: false - Layout/FirstHashElementIndentation: Enabled: false diff --git a/it/ruby/spec/basic/integration_test_basic.rb b/it/ruby/spec/basic/integration_test_basic.rb index 11aface28b..56497f1fb6 100644 --- a/it/ruby/spec/basic/integration_test_basic.rb +++ b/it/ruby/spec/basic/integration_test_basic.rb @@ -7,7 +7,7 @@ request_adapter.set_base_url('http://127.0.0.1:1080') client = Integration_test::Client::ApiClient.new(request_adapter) expect(client).to_not be nil - + # Error: uninitialized constant Integration_test::Client::Api::V1::Topics::TopicsRequestBuilder::Binary # response = client.api().v1().topics().get().resume # pp response diff --git a/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb b/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb index 533e47d74a..ce77368990 100644 --- a/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb +++ b/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb @@ -6,25 +6,25 @@ request_adapter = MicrosoftKiotaFaraday::FaradayRequestAdapter.new(auth_provider) request_adapter.set_base_url('http://127.0.0.1:1080') client = Integration_test::Client::ApiClient.new(request_adapter) - + service_response = client.api().v1().weather_forecast().get().resume # Here, a single object is returned instead of a list. So we just check for null expect(service_response).to_not be nil - + # pp service_response # pp service_response.enum_value().class - + # Now the real test: create a model class and verify that all properties have the default values. model = Integration_test::Client::Models::WeatherForecast.new() - + expect(model.bool_value()).to be true expect(model.date_only_value).to_not be nil expect(model.date_only_value.to_s()).to eq("1900-01-01") - + expect(model.date_value).to_not be nil expect(model.date_value.to_s()).to eq("1900-01-01T00:00:00+00:00") - + expect(model.decimal_value()).to be 25.5 expect(model.double_value()).to be 25.5 expect(model.enum_value()).to be Integration_test::Client::Models::WeatherForecastEnumValue[:One] @@ -32,11 +32,11 @@ expect(model.guid_value).to_not be nil expect(model.guid_value().to_s()).to eq("00000000-0000-0000-0000-000000000000") - + expect(model.long_value()).to be 255 expect(model.summary()).to eq("Test") expect(model.temperature_c()).to be 15 - + expect(model.time_value()).to_not be nil expect(model.time_value().strftime("%H:%M:%S")).to eq("00:00:00") end diff --git a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs index cad3ae39f0..f560e7dbb5 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs @@ -639,23 +639,22 @@ private void WriteMethodDocumentation(CodeMethod code, LanguageWriter writer) var parametersWithDescription = code.Parameters.Where(static x => x.Documentation.DescriptionAvailable).OrderBy(static x => x.Name, StringComparer.OrdinalIgnoreCase).ToArray(); if (code.Documentation.DescriptionAvailable || parametersWithDescription.Length != 0) { - writer.WriteLine(conventions.DocCommentStart); if (code.Documentation.DescriptionAvailable) { var description = code.Documentation.GetDescription(type => conventions.GetTypeString(type, code), normalizationFunc: RubyConventionService.RemoveInvalidDescriptionCharacters); - writer.WriteLine($"{conventions.DocCommentPrefix}{description}"); + if (!string.IsNullOrWhiteSpace(description)) + writer.WriteLine($"{conventions.DocCommentPrefix}{description}"); } foreach (var paramWithDescription in parametersWithDescription) { var description = paramWithDescription.Documentation.GetDescription(type => conventions.GetTypeString(type, code), normalizationFunc: RubyConventionService.RemoveInvalidDescriptionCharacters); - writer.WriteLine($"{conventions.DocCommentPrefix}@param {paramWithDescription.Name.ToSnakeCase()} {description}"); + writer.WriteLine($"{conventions.DocCommentPrefix}@param {paramWithDescription.Name.ToSnakeCase()} {description}".TrimEnd()); } if (code.IsAsync) writer.WriteLine($"{conventions.DocCommentPrefix}@return a Fiber of {code.ReturnType.Name.ToSnakeCase()}"); else writer.WriteLine($"{conventions.DocCommentPrefix}@return a {code.ReturnType.Name.ToSnakeCase()}"); - writer.WriteLine(conventions.DocCommentEnd); } } private string GetDeserializationMethodName(CodeTypeBase propType) diff --git a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs index 1ac31b5bf3..f343ec0ae9 100644 --- a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs +++ b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs @@ -12,10 +12,8 @@ public class RubyConventionService : CommonLanguageConventionService public override string StreamTypeName => "stdin"; private const string InternalVoidTypeName = "nil"; public override string VoidTypeName => InternalVoidTypeName; - public override string DocCommentPrefix => "## "; + public override string DocCommentPrefix => "# "; public override string ParseNodeInterfaceName => "parse_node"; - internal string DocCommentStart = "## "; - internal string DocCommentEnd = "## "; public override string TempDictionaryVarName => "url_tpl_params"; // a namespace barrel autoloads these, so their files are only ever loaded through it internal static bool IsAutoloaded(CodeElement element) => element switch @@ -83,9 +81,8 @@ public override bool WriteShortDescription(IDocumentedElement element, LanguageW if (element is not CodeElement codeElement) return false; var description = element.Documentation.GetDescription(type => GetTypeString(type, codeElement), normalizationFunc: RemoveInvalidDescriptionCharacters); - writer.WriteLine($"{DocCommentPrefix}"); - writer.WriteLine($"# {description}"); - + if (string.IsNullOrWhiteSpace(description)) return false; + writer.WriteLine($"{DocCommentPrefix}{description}"); return true; } #pragma warning disable CA1822 // Method should be static @@ -112,7 +109,8 @@ internal static string RemoveInvalidDescriptionCharacters(string originalDescrip originalDescription.Replace("\\", "#", StringComparison.OrdinalIgnoreCase) .Replace("\r", string.Empty, StringComparison.Ordinal) .Replace("\n", string.Empty, StringComparison.Ordinal) - .Replace("\t", " ", StringComparison.Ordinal); + .Replace("\t", " ", StringComparison.Ordinal) + .Trim(); #pragma warning disable CA1822 // Method should be static internal void AddRequestBuilderBody(CodeClass parentClass, string returnType, LanguageWriter writer, string? urlTemplateVarName = default, string? prefix = default, IEnumerable? pathParameters = default) { diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs index aae0e9a73f..9bf46df63c 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs @@ -888,6 +888,24 @@ public void WritesMethodSyncDescription() AssertExtensions.CurlyBracesAreClosed(result); } [Fact] + public void WritesYardDocumentationWithoutTrailingWhitespace() + { + setup(); + method.Documentation.DescriptionTemplate = $"{MethodDescription} "; + method.AddParameter(new CodeParameter + { + Documentation = new() { DescriptionTemplate = ParamDescription }, + Name = ParamName, + Type = new CodeType { Name = "string" }, + }); + writer.Write(method); + var result = tw.ToString(); + Assert.DoesNotContain("##", result, StringComparison.Ordinal); + Assert.Contains($"# {MethodDescription}{Environment.NewLine}", result, StringComparison.Ordinal); + Assert.Contains($"# @param {ParamName.ToSnakeCase()} {ParamDescription}", result, StringComparison.Ordinal); + Assert.DoesNotContain(result.Split(Environment.NewLine), static x => x.Length != x.TrimEnd().Length); + } + [Fact] public void Defensive() { setup(); From 67c32ec6fe242af836377aef90abbb103a506a6a Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 11:50:47 +0100 Subject: [PATCH 04/25] fix(ruby): expose model properties with attr_accessor instead of bare instance variables --- it/ruby/.rubocop.yml | 17 +++-------------- src/Kiota.Builder/Refiners/RubyRefiner.cs | 12 ------------ .../Writers/Ruby/CodePropertyWriter.cs | 7 +++++++ .../Refiners/RubyLanguageRefinerTests.cs | 9 +++++++++ .../Writers/Ruby/CodePropertyWriterTests.cs | 4 +++- 5 files changed, 22 insertions(+), 27 deletions(-) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index 9342e78eec..abd62db607 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -35,9 +35,6 @@ Layout/EmptyLineBetweenDefs: Style/MutableConstant: Enabled: false -Lint/Void: - Enabled: false - Style/Documentation: Enabled: false @@ -56,9 +53,6 @@ Style/MethodCallWithoutArgsParentheses: Style/TrailingCommaInHashLiteral: Enabled: false -Style/TrivialAccessors: - Enabled: false - Naming/ClassAndModuleCamelCase: Enabled: false @@ -86,9 +80,6 @@ Lint/EmptyFile: Style/MixinGrouping: Enabled: false -Style/AccessorGrouping: - Enabled: false - Layout/SpaceInsideHashLiteralBraces: Enabled: false @@ -134,8 +125,6 @@ Metrics/PerceivedComplexity: Lint/UselessMethodDefinition: Enabled: false -# The cop matches by method name, so it flags the accessor for an API property called `inherited` -# (the GitHub description has one). Ruby's inheritance hook is a class method, and an instance -# method of the same name does not shadow it, so renaming the property would be the worse trade -Lint/MissingSuper: - Enabled: false +# one accessor per property, each with its own doc comment +Style/AccessorGrouping: + EnforcedStyle: separated diff --git a/src/Kiota.Builder/Refiners/RubyRefiner.cs b/src/Kiota.Builder/Refiners/RubyRefiner.cs index 361c077a41..416f87f8a3 100644 --- a/src/Kiota.Builder/Refiners/RubyRefiner.cs +++ b/src/Kiota.Builder/Refiners/RubyRefiner.cs @@ -81,18 +81,6 @@ public override Task RefineAsync(CodeNamespace generatedCode, CancellationToken true ); ReplaceReservedNames(generatedCode, reservedNamesProvider, x => $"{x}_escaped"); - AddGetterAndSetterMethods(generatedCode, - [ - CodePropertyKind.Custom, - CodePropertyKind.AdditionalData, - CodePropertyKind.BackingStore, - ], - static (_, s) => s.ToSnakeCase(), - _configuration.UsesBackingStore, - true, - string.Empty, - string.Empty, - string.Empty); AddConstructorsForDefaultValues( generatedCode, true, diff --git a/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs index 695c0cb164..8caf13f5d3 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs @@ -29,6 +29,13 @@ public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter w case CodePropertyKind.Options: writer.WriteLine($"attr_accessor :{codeElement.Name.ToSnakeCase()}"); break; + case CodePropertyKind.Custom: + case CodePropertyKind.AdditionalData: + case CodePropertyKind.BackingStore: + // a model always has methods after its properties, so this never precedes the class end + writer.WriteLine($"attr_accessor :{codeElement.Name.ToSnakeCase()}"); + writer.WriteLine(); + break; default: writer.WriteLine($"@{codeElement.NamePrefix}{codeElement.Name.ToSnakeCase()}"); break; diff --git a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs index 8c030637bd..a6ee5b8376 100644 --- a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs +++ b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs @@ -132,6 +132,15 @@ public async Task RequiresARequestBuilderFromTheSameNamespaceAsync() Assert.Contains(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == emptySegment); } [Fact] + public async Task DoesNotAddAccessorMethodsForModelPropertiesAsync() + { + var model = graphNS.AddClass(new CodeClass { Name = "animal", Kind = CodeClassKind.Model }).First(); + model.AddProperty(new CodeProperty { Name = "name", Kind = CodePropertyKind.Custom, Type = new CodeType { Name = "string" } }); + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.DoesNotContain(model.Methods, static x => x.IsOfKind(CodeMethodKind.Getter, CodeMethodKind.Setter)); + Assert.Contains(model.Properties, static x => x.IsOfKind(CodePropertyKind.Custom)); + } + [Fact] public async Task DoesNotKeepCancellationParametersInRequestExecutorsAsync() { var model = root.AddClass(new CodeClass diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodePropertyWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodePropertyWriterTests.cs index 2bb28b27b1..985e3f1840 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodePropertyWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodePropertyWriterTests.cs @@ -134,6 +134,8 @@ public void WritesCustomProperty() property.Kind = CodePropertyKind.Custom; writer.Write(property); var result = tw.ToString(); - Assert.Contains($"@{PropertyName.ToSnakeCase()}", result); + Assert.Contains($"attr_accessor :{PropertyName.ToSnakeCase()}", result); + // a bare instance variable in a class body declares nothing and warns under ruby -w + Assert.DoesNotContain($"@{PropertyName.ToSnakeCase()}", result); } } From 6ab5384d1fac6253ec7dff611266e73d1b0744be Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 11:53:28 +0100 Subject: [PATCH 05/25] style(ruby): freeze generated enum hashes --- it/ruby/.rubocop.yml | 3 --- src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs | 2 +- tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs | 1 + 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index abd62db607..c9901d651d 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -32,9 +32,6 @@ Style/IfUnlessModifier: Layout/EmptyLineBetweenDefs: Enabled: false -Style/MutableConstant: - Enabled: false - Style/Documentation: Enabled: false diff --git a/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs index 76e3a32a82..51791f04d8 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs @@ -20,7 +20,7 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write conventions.WriteShortDescription(codeElement, writer); writer.StartBlock($"{codeElement.Name.ToFirstCharacterUpperCase()} = {{"); codeElement.Options.ToList().ForEach(x => writer.WriteLine($"{x.Name.ToFirstCharacterUpperCase()}: :{x.Name.ToFirstCharacterUpperCase()},")); - writer.CloseBlock(); + writer.CloseBlock("}.freeze"); if (codeElement.Parent is CodeNamespace ns2) conventions.WriteNamespaceClosing(ns2, writer); } diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs index 0e2e74d9fb..8d882000f6 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs @@ -46,6 +46,7 @@ public void WritesEnum() var result = tw.ToString(); Assert.Contains("= {", result); Assert.Contains(optionName, result); + Assert.Contains("}.freeze", result); AssertExtensions.CurlyBracesAreClosed(result); } [Fact] From 23a3ec453552823d56543b78f9820c714f05e36f Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 11:56:30 +0100 Subject: [PATCH 06/25] test(ruby): lint the layout cops generated code already satisfies - stop linting comment annotations, since API descriptions can start with "Note:" --- it/ruby/.rubocop.yml | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index c9901d651d..613db0198f 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -56,21 +56,12 @@ Naming/ClassAndModuleCamelCase: Naming/AccessorMethodName: Enabled: false -Layout/IndentationStyle: - Enabled: false - Layout/SpaceAroundEqualsInParameterDefault: Enabled: false Style/RedundantSelf: Enabled: false -Layout/FirstArgumentIndentation: - Enabled: false - -Layout/ClosingParenthesisIndentation: - Enabled: false - Lint/EmptyFile: Enabled: false @@ -80,9 +71,6 @@ Style/MixinGrouping: Layout/SpaceInsideHashLiteralBraces: Enabled: false -Layout/TrailingEmptyLines: - Enabled: false - Metrics/MethodLength: Enabled: false @@ -125,3 +113,7 @@ Lint/UselessMethodDefinition: # one accessor per property, each with its own doc comment Style/AccessorGrouping: EnforcedStyle: separated + +# descriptions come from the API and may start with prose such as "Note:" +Style/CommentAnnotation: + Enabled: false From d97b800a3f9c9afc7889ef0af070b5d88fc6f196 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 11:59:53 +0100 Subject: [PATCH 07/25] fix(ruby): write the client barrel where files require it for a multi-segment namespace - remove the IT bridge file that was hiding the misplaced barrel --- CHANGELOG.md | 1 + it/exec-cmd.ps1 | 3 --- it/ruby/client.rb | 6 ------ it/ruby/lib/integration_test.rb | 2 +- it/ruby/lib/integration_test/client/client.rb | 6 ------ .../PathSegmenters/CommonPathSegmenter.cs | 2 +- .../PathSegmenters/RubyPathSegmenter.cs | 3 +++ .../PathSegmenters/RubyPathSegmenterTests.cs | 21 +++++++++++++++++++ 8 files changed, 27 insertions(+), 17 deletions(-) delete mode 100644 it/ruby/client.rb delete mode 100644 it/ruby/lib/integration_test/client/client.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index cfc8012beb..bd603e4f18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Preserve models for multipart properties with default content types when other properties specify an encoding. [#7342](https://github.com/microsoft/kiota/issues/7342) - Dart: escape enum options named value or values to avoid conflicts with generated and built-in enum members. [#7807](https://github.com/microsoft/kiota/issues/7807) +- Ruby: a client generated with a multi-segment `--namespace-name`, such as `integration_test.client`, failed to load because its root file was written one directory too deep. - Ruby: namespace barrels register their models and enums with `autoload` instead of requiring them, so a subclass no longer fails to load when its base class file is required first. Other files require the barrel rather than an individual model file, and models now load on first use. [#7956](https://github.com/microsoft/kiota/issues/7956) - C#: escape Unicode line and paragraph separators in generated string literals so generated clients remain valid C# source. - External reference allowlist wildcards no longer cross the URI authority boundary, so a wildcard in the scheme or host cannot match text in the path, the user information or the port. diff --git a/it/exec-cmd.ps1 b/it/exec-cmd.ps1 index 209f9f07f7..375cb60fa2 100755 --- a/it/exec-cmd.ps1 +++ b/it/exec-cmd.ps1 @@ -232,9 +232,6 @@ elseif ($language -eq "typescript") { } -ErrorAction Stop } elseif ($language -eq "ruby") { - $clientRb = Join-Path -Path $testPath -ChildPath "client.rb" - $dest = Join-Path -Path $testPath -ChildPath "lib" -AdditionalChildPath "integration_test", "client" - Copy-Item -Path $clientRb -Destination $dest # Mock server tests are places in a subdir in "spec". So execute them. if ($mockServerTest) { Invoke-call -ScriptBlock { diff --git a/it/ruby/client.rb b/it/ruby/client.rb deleted file mode 100644 index 87a5aa7bd0..0000000000 --- a/it/ruby/client.rb +++ /dev/null @@ -1,6 +0,0 @@ -require_relative "api_client" - -module Integration_test - module Client - end -end diff --git a/it/ruby/lib/integration_test.rb b/it/ruby/lib/integration_test.rb index 3109eb88da..dc5c0c23e8 100644 --- a/it/ruby/lib/integration_test.rb +++ b/it/ruby/lib/integration_test.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require_relative "integration_test/version" -require_relative "integration_test/client/client" +require_relative "integration_test/client/api_client" module Integration_test class Error < StandardError; end diff --git a/it/ruby/lib/integration_test/client/client.rb b/it/ruby/lib/integration_test/client/client.rb deleted file mode 100644 index 3f69625626..0000000000 --- a/it/ruby/lib/integration_test/client/client.rb +++ /dev/null @@ -1,6 +0,0 @@ -require_relative "api_client" - -module Integration_test - module Client - end -end diff --git a/src/Kiota.Builder/PathSegmenters/CommonPathSegmenter.cs b/src/Kiota.Builder/PathSegmenters/CommonPathSegmenter.cs index bded505add..84c80404a7 100644 --- a/src/Kiota.Builder/PathSegmenters/CommonPathSegmenter.cs +++ b/src/Kiota.Builder/PathSegmenters/CommonPathSegmenter.cs @@ -33,7 +33,7 @@ public abstract string FileSuffix public virtual string NormalizePath(string fullPath) => fullPath; public virtual IEnumerable GetAdditionalSegment(CodeElement currentElement, string fileName) => Enumerable.Empty(); protected static string GetLastFileNameSegment(CodeElement currentElement) => currentElement?.Name.Split('.')[^1] ?? string.Empty; - public string GetPath(CodeNamespace currentNamespace, CodeElement currentElement, bool shouldNormalizePath = true) + public virtual string GetPath(CodeNamespace currentNamespace, CodeElement currentElement, bool shouldNormalizePath = true) { ArgumentNullException.ThrowIfNull(currentNamespace); var fileName = NormalizeFileName(currentElement); diff --git a/src/Kiota.Builder/PathSegmenters/RubyPathSegmenter.cs b/src/Kiota.Builder/PathSegmenters/RubyPathSegmenter.cs index c6386ab133..1182cebfcc 100644 --- a/src/Kiota.Builder/PathSegmenters/RubyPathSegmenter.cs +++ b/src/Kiota.Builder/PathSegmenters/RubyPathSegmenter.cs @@ -20,6 +20,9 @@ public override IEnumerable GetAdditionalSegment(CodeElement currentElem }; } public override string FileSuffix => ".rb"; + // the client barrel belongs at the output root, where every file requires it + public override string GetPath(CodeNamespace currentNamespace, CodeElement currentElement, bool shouldNormalizePath = true) => + base.GetPath(currentElement is CodeNamespace ns && ClientNamespaceName.Equals(ns.Name, StringComparison.OrdinalIgnoreCase) ? ns : currentNamespace, currentElement, shouldNormalizePath); private readonly ConcurrentDictionary> collidingFileNames = new(); /// /// Snake casing is lossy: names that differ only in where a separator falls, such as diff --git a/tests/Kiota.Builder.Tests/PathSegmenters/RubyPathSegmenterTests.cs b/tests/Kiota.Builder.Tests/PathSegmenters/RubyPathSegmenterTests.cs index 7309fa3988..7f02189adf 100644 --- a/tests/Kiota.Builder.Tests/PathSegmenters/RubyPathSegmenterTests.cs +++ b/tests/Kiota.Builder.Tests/PathSegmenters/RubyPathSegmenterTests.cs @@ -13,6 +13,27 @@ public RubyPathSegmenterTests() segmenter = new RubyPathSegmenter("/tmp/kiota-sample", "client"); } + [Fact] + public void WritesTheClientBarrelWhereFilesRequireItForAMultiSegmentNamespace() + { + var multiSegment = new RubyPathSegmenter("/tmp/kiota-sample", "integration_test.client"); + var rootNamespace = CodeNamespace.InitRootNamespace(); + var parent = rootNamespace.AddNamespace("integration_test"); + var client = parent.AddNamespace("integration_test.client"); + var models = client.AddNamespace("integration_test.client.models"); + // the renderer passes the parent namespace, whose name is only a prefix of the client's + Assert.Equal(System.IO.Path.Combine("/tmp/kiota-sample", "client.rb"), multiSegment.GetPath(parent, client)); + Assert.Equal(System.IO.Path.Combine("/tmp/kiota-sample", "models", "models.rb"), multiSegment.GetPath(client, models)); + } + + [Fact] + public void WritesTheClientBarrelAtTheRootForASingleSegmentNamespace() + { + var rootNamespace = CodeNamespace.InitRootNamespace(); + var client = rootNamespace.AddNamespace("client"); + Assert.Equal(System.IO.Path.Combine("/tmp/kiota-sample", "client.rb"), segmenter.GetPath(rootNamespace, client)); + } + [Fact] public void RubyPathSegmenterGeneratesCorrectFileName() { From c61b19c7261dd66b713638d823fbe670cb6e4eb6 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 12:06:14 +0100 Subject: [PATCH 08/25] fix(ruby): stop writing and requiring barrels that have nothing to autoload --- CHANGELOG.md | 1 + .../CodeRenderers/CodeRenderer.cs | 1 + .../CodeRenderers/RubyCodeRenderer.cs | 12 +++++ src/Kiota.Builder/Refiners/RubyRefiner.cs | 4 ++ .../Writers/Ruby/RubyConventionService.cs | 3 ++ .../CodeRenderers/RubyCodeRendererTests.cs | 52 +++++++++++++++++++ .../Refiners/RubyLanguageRefinerTests.cs | 16 ++++-- 7 files changed, 86 insertions(+), 3 deletions(-) create mode 100644 src/Kiota.Builder/CodeRenderers/RubyCodeRenderer.cs create mode 100644 tests/Kiota.Builder.Tests/CodeRenderers/RubyCodeRendererTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index bd603e4f18..eac7aaa93f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Preserve models for multipart properties with default content types when other properties specify an encoding. [#7342](https://github.com/microsoft/kiota/issues/7342) - Dart: escape enum options named value or values to avoid conflicts with generated and built-in enum members. [#7807](https://github.com/microsoft/kiota/issues/7807) +- Ruby: namespaces with nothing to autoload no longer get an empty barrel file, and generated files no longer require them (561 fewer files in a GitHub client). - Ruby: a client generated with a multi-segment `--namespace-name`, such as `integration_test.client`, failed to load because its root file was written one directory too deep. - Ruby: namespace barrels register their models and enums with `autoload` instead of requiring them, so a subclass no longer fails to load when its base class file is required first. Other files require the barrel rather than an individual model file, and models now load on first use. [#7956](https://github.com/microsoft/kiota/issues/7956) - C#: escape Unicode line and paragraph separators in generated string literals so generated clients remain valid C# source. diff --git a/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs b/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs index 4636ad27e6..7a48c38b40 100644 --- a/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs +++ b/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs @@ -103,6 +103,7 @@ public static CodeRenderer GetCodeRender(GenerationConfiguration config) return config.Language switch { GenerationLanguage.TypeScript => new TypeScriptCodeRenderer(config), + GenerationLanguage.Ruby => new RubyCodeRenderer(config), GenerationLanguage.Python => new CodeRenderer(config, new CodeElementOrderComparerPython()), GenerationLanguage.Go => new CodeRenderer(config, new CodeElementOrderComparerWithExternalMethods()), _ => new CodeRenderer(config), diff --git a/src/Kiota.Builder/CodeRenderers/RubyCodeRenderer.cs b/src/Kiota.Builder/CodeRenderers/RubyCodeRenderer.cs new file mode 100644 index 0000000000..7261823053 --- /dev/null +++ b/src/Kiota.Builder/CodeRenderers/RubyCodeRenderer.cs @@ -0,0 +1,12 @@ +using Kiota.Builder.CodeDOM; +using Kiota.Builder.Configuration; +using Kiota.Builder.Writers.Ruby; + +namespace Kiota.Builder.CodeRenderers; + +public class RubyCodeRenderer : CodeRenderer +{ + public RubyCodeRenderer(GenerationConfiguration configuration) : base(configuration) { } + public override bool ShouldRenderNamespaceFile(CodeNamespace codeNamespace) => + codeNamespace is not null && base.ShouldRenderNamespaceFile(codeNamespace) && RubyConventionService.HasAutoloadedMembers(codeNamespace); +} diff --git a/src/Kiota.Builder/Refiners/RubyRefiner.cs b/src/Kiota.Builder/Refiners/RubyRefiner.cs index 416f87f8a3..cc9f0233d8 100644 --- a/src/Kiota.Builder/Refiners/RubyRefiner.cs +++ b/src/Kiota.Builder/Refiners/RubyRefiner.cs @@ -287,6 +287,10 @@ private static void RequireBarrelsOfAutoloadedTypes(CodeElement currentElement) { if (currentElement is CodeClass { Parent: CodeNamespace currentNamespace } currentClass) { + // a namespace with nothing to autoload gets no barrel file, so nothing may require one + currentClass.StartBlock.RemoveUsings(currentClass.Usings + .Where(static x => !x.IsExternal && x.Declaration?.TypeDefinition is CodeNamespace ns && !RubyConventionService.HasAutoloadedMembers(ns)) + .ToArray()); var typeUsings = currentClass.Usings .Where(static x => !x.IsExternal && x.Declaration?.TypeDefinition is CodeElement definition && RubyConventionService.IsAutoloaded(definition)) .ToArray(); diff --git a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs index f343ec0ae9..69bf9ac697 100644 --- a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs +++ b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs @@ -22,6 +22,9 @@ public class RubyConventionService : CommonLanguageConventionService CodeEnum codeEnum => codeEnum.Parent is CodeNamespace ns && !ns.HasClassNamedAfterItself() && codeEnum.Options.Any(), _ => false, }; + // a barrel is written, and required, only when it has something to autoload + internal static bool HasAutoloadedMembers(CodeNamespace codeNamespace) => + codeNamespace.Classes.Any(IsAutoloaded) || codeNamespace.Enums.Any(IsAutoloaded); internal static string SanitizeRubyDoubleQuoteLiteral(string? value) { if (string.IsNullOrEmpty(value)) return string.Empty; diff --git a/tests/Kiota.Builder.Tests/CodeRenderers/RubyCodeRendererTests.cs b/tests/Kiota.Builder.Tests/CodeRenderers/RubyCodeRendererTests.cs new file mode 100644 index 0000000000..92f94b890f --- /dev/null +++ b/tests/Kiota.Builder.Tests/CodeRenderers/RubyCodeRendererTests.cs @@ -0,0 +1,52 @@ +using System.Linq; + +using Kiota.Builder.CodeDOM; +using Kiota.Builder.CodeRenderers; +using Kiota.Builder.Configuration; + +using Xunit; + +namespace Kiota.Builder.Tests.CodeRenderers; + +public class RubyCodeRendererTests +{ + private readonly RubyCodeRenderer renderer = new(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = "graph" }); + private readonly CodeNamespace root = CodeNamespace.InitRootNamespace(); + + [Fact] + public void IsTheRendererForRuby() => + Assert.IsType(CodeRenderer.GetCodeRender(new GenerationConfiguration { Language = GenerationLanguage.Ruby })); + + [Fact] + public void SkipsTheBarrelOfANamespaceWithOnlyRequestBuilders() + { + var ns = root.AddNamespace("graph.users"); + ns.AddClass(new CodeClass { Name = "usersRequestBuilder", Kind = CodeClassKind.RequestBuilder }); + Assert.False(renderer.ShouldRenderNamespaceFile(ns)); + } + + [Fact] + public void WritesTheBarrelOfANamespaceWithAModel() + { + var ns = root.AddNamespace("graph.models"); + ns.AddClass(new CodeClass { Name = "user", Kind = CodeClassKind.Model }); + Assert.True(renderer.ShouldRenderNamespaceFile(ns)); + } + + [Fact] + public void WritesTheBarrelOfANamespaceWithAnEnumThatHasOptions() + { + var ns = root.AddNamespace("graph.models"); + ns.AddEnum(new CodeEnum { Name = "color" }).First().AddOption(new CodeEnumOption { Name = "red" }); + Assert.True(renderer.ShouldRenderNamespaceFile(ns)); + } + + [Fact] + public void SkipsTheBarrelWhenAClassTakesItsFile() + { + var ns = root.AddNamespace("graph.models"); + ns.AddClass(new CodeClass { Name = "models", Kind = CodeClassKind.Model }); + ns.AddClass(new CodeClass { Name = "user", Kind = CodeClassKind.Model }); + Assert.False(renderer.ShouldRenderNamespaceFile(ns)); + } +} diff --git a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs index a6ee5b8376..aced767e1f 100644 --- a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs +++ b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs @@ -33,7 +33,8 @@ public async Task DoesNotRequireItsOwnBarrelFromAnAutoloadedModelAsync() var model = modelsNS.AddClass(new CodeClass { Name = "animal", Kind = CodeClassKind.Model }).First(); await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); Assert.DoesNotContain(model.Usings, x => x.Declaration?.TypeDefinition == modelsNS); - Assert.Contains(model.Usings, x => x.Declaration?.TypeDefinition == graphNS); + // the root namespace autoloads nothing here, so it gets no barrel to require + Assert.DoesNotContain(model.Usings, x => x.Declaration?.TypeDefinition == graphNS); } [Fact] public async Task RequiresTheBarrelOfAModelUsedFromAnotherNamespaceAsync() @@ -51,7 +52,7 @@ public async Task RequiresTheBarrelOfAModelUsedFromAnotherNamespaceAsync() await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); Assert.DoesNotContain(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == model); Assert.Contains(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == modelsNS); - Assert.Contains(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == animalsNS); + Assert.DoesNotContain(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == animalsNS); } [Fact] public async Task RequiresTheBarrelOfABaseClassInAnotherNamespaceAsync() @@ -67,6 +68,15 @@ public async Task RequiresTheBarrelOfABaseClassInAnotherNamespaceAsync() Assert.DoesNotContain(derivedModel.Usings, x => x.Declaration?.TypeDefinition == reposNS); } [Fact] + public async Task KeepsItsOwnBarrelWhenTheNamespaceAutoloadsSomethingAsync() + { + var animalsNS = graphNS.AddNamespace($"{graphNS.Name}.animals"); + var requestBuilder = animalsNS.AddClass(new CodeClass { Name = "animalsRequestBuilder", Kind = CodeClassKind.RequestBuilder }).First(); + animalsNS.AddClass(new CodeClass { Name = "animalsGetResponse", Kind = CodeClassKind.Model }); + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.Contains(requestBuilder.Usings, x => x.Declaration?.TypeDefinition == animalsNS); + } + [Fact] public async Task RequiresTheModelDirectlyWhenItsNamespaceHasNoBarrelAsync() { // a class named after its namespace takes the barrel's file, so there is nothing to autoload from @@ -442,7 +452,7 @@ public async Task AddNamespaceModuleImportsAsync() }); await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); Assert.Single(declaration.Usings, static x => "Message".Equals(x.Declaration.Name, StringComparison.OrdinalIgnoreCase)); - Assert.Single(declaration.Usings, static x => "graph".Equals(x.Declaration.Name, StringComparison.OrdinalIgnoreCase)); + Assert.DoesNotContain(declaration.Usings, static x => "graph".Equals(x.Declaration.Name, StringComparison.OrdinalIgnoreCase)); } [Fact] public async Task ShortensLongNamespaceNamesAsync() From b750a755e1569edc0e422a1c2fbdba17e70b2a30 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 12:12:02 +0100 Subject: [PATCH 09/25] style(ruby): write lambdas, hashes and mixins the idiomatic way - stabby lambdas and {} instead of lambda blocks and Hash.new - no trailing comma on the last hash entry, and super or {} for models with no fields of their own - one include per line, in the order that keeps method lookup unchanged --- it/ruby/.rubocop.yml | 21 ----------- src/Kiota.Builder/Refiners/RubyRefiner.cs | 2 +- .../Ruby/CodeClassDeclarationWriter.cs | 4 +- .../Writers/Ruby/CodeEnumWriter.cs | 4 +- .../Writers/Ruby/CodeMethodWriter.cs | 37 ++++++++++--------- .../Refiners/RubyLanguageRefinerTests.cs | 2 +- .../Ruby/CodeClassDeclarationWriterTests.cs | 11 ++++++ .../Writers/Ruby/CodeEnumWriterTests.cs | 1 + .../Writers/Ruby/CodeMethodWriterTests.cs | 13 ++++--- 9 files changed, 46 insertions(+), 49 deletions(-) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index 613db0198f..d6f55d74b5 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -11,15 +11,6 @@ Style/StringLiteralsInInterpolation: Layout/LineLength: Enabled: false -Layout/FirstHashElementIndentation: - Enabled: false - -Layout/SpaceInsideBlockBraces: - Enabled: false - -Style/Lambda: - Enabled: false - Style/DefWithParentheses: Enabled: false @@ -38,18 +29,12 @@ Style/Documentation: Style/FrozenStringLiteralComment: Enabled: false -Style/EmptyLiteral: - Enabled: false - Layout/EmptyLineAfterGuardClause: Enabled: false Style/MethodCallWithoutArgsParentheses: Enabled: false -Style/TrailingCommaInHashLiteral: - Enabled: false - Naming/ClassAndModuleCamelCase: Enabled: false @@ -65,12 +50,6 @@ Style/RedundantSelf: Lint/EmptyFile: Enabled: false -Style/MixinGrouping: - Enabled: false - -Layout/SpaceInsideHashLiteralBraces: - Enabled: false - Metrics/MethodLength: Enabled: false diff --git a/src/Kiota.Builder/Refiners/RubyRefiner.cs b/src/Kiota.Builder/Refiners/RubyRefiner.cs index cc9f0233d8..8946a03be6 100644 --- a/src/Kiota.Builder/Refiners/RubyRefiner.cs +++ b/src/Kiota.Builder/Refiners/RubyRefiner.cs @@ -221,7 +221,7 @@ private static void CorrectPropertyType(CodeProperty currentProperty) { currentProperty.Type.IsNullable = true; if (!string.IsNullOrEmpty(currentProperty.DefaultValue)) - currentProperty.DefaultValue = "Hash.new"; + currentProperty.DefaultValue = "{}"; } CorrectCoreTypes(currentProperty.Parent as CodeClass, DateTypesReplacements, types: currentProperty.Type); diff --git a/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs index 7f101c25b4..ffb3b85894 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs @@ -59,6 +59,8 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit writer.StartBlock($"class {codeElement.Name.ToFirstCharacterUpperCase()}{derivation}"); // writing an empty mixin line would leave a blank (indent-only) first line in the class body if (codeElement.Implements.Any()) - writer.WriteLine($"include {codeElement.Implements.Select(static x => x.Name).Aggregate(static (x, y) => x + ", " + y)}"); + // `include A, B` is `include B` then `include A`, so the order keeps method lookup unchanged + foreach (var mixin in codeElement.Implements.Select(static x => x.Name).Reverse()) + writer.WriteLine($"include {mixin}"); } } diff --git a/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs index 51791f04d8..982511c936 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs @@ -19,7 +19,9 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write conventions.WriteNamespaceModules(ns, writer); conventions.WriteShortDescription(codeElement, writer); writer.StartBlock($"{codeElement.Name.ToFirstCharacterUpperCase()} = {{"); - codeElement.Options.ToList().ForEach(x => writer.WriteLine($"{x.Name.ToFirstCharacterUpperCase()}: :{x.Name.ToFirstCharacterUpperCase()},")); + var options = codeElement.Options.Select(static x => $"{x.Name.ToFirstCharacterUpperCase()}: :{x.Name.ToFirstCharacterUpperCase()}").ToArray(); + for (var i = 0; i < options.Length; i++) + writer.WriteLine(i < options.Length - 1 ? $"{options[i]}," : options[i]); writer.CloseBlock("}.freeze"); if (codeElement.Parent is CodeNamespace ns2) conventions.WriteNamespaceClosing(ns2, writer); diff --git a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs index f560e7dbb5..9043f04459 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs @@ -291,7 +291,7 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho if (currentMethod.Parameters.OfKind(CodeParameterKind.PathParameters) is CodeParameter pathParametersParameter) writer.WriteLine($"super({pathParametersParameter.Name.ToSnakeCase()}, {requestAdapterParameter.Name.ToSnakeCase()}, {sanitizedUrlTemplate})"); else - writer.WriteLine($"super(Hash.new, {requestAdapterParameter.Name.ToSnakeCase()}, {sanitizedUrlTemplate})"); + writer.WriteLine($"super({{}}, {requestAdapterParameter.Name.ToSnakeCase()}, {sanitizedUrlTemplate})"); } else writer.WriteLine("super"); @@ -392,22 +392,23 @@ private void WriteDeserializerBody(CodeClass parentClass, LanguageWriter writer) } private void WriteDeserializerBodyForInheritedModel(CodeClass parentClass, LanguageWriter writer) { - if (parentClass.StartBlock.Inherits != null) - writer.WriteLine("return super.merge({"); - else - writer.WriteLine("return {"); - writer.IncreaseIndent(); - foreach (var otherProp in parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) - .Where(static x => !x.ExistsInBaseType) - .OrderBy(static x => x.Name)) - { - writer.WriteLine($"\"{RubyConventionService.SanitizeRubyDoubleQuoteLiteral(otherProp.WireName)}\" => lambda {{|n| @{otherProp.NamePrefix}{otherProp.Name.ToSnakeCase()} = n.{GetDeserializationMethodName(otherProp.Type)} }},"); + var inherits = parentClass.StartBlock.Inherits != null; + var entries = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) + .Where(static x => !x.ExistsInBaseType) + .OrderBy(static x => x.Name) + .Select(x => $"\"{RubyConventionService.SanitizeRubyDoubleQuoteLiteral(x.WireName)}\" => ->(n) {{ @{x.NamePrefix}{x.Name.ToSnakeCase()} = n.{GetDeserializationMethodName(x.Type)} }}") + .ToArray(); + if (entries.Length == 0) + { + writer.WriteLine(inherits ? "return super" : "return {}"); + return; } + writer.WriteLine(inherits ? "return super.merge(" : "return {"); + writer.IncreaseIndent(); + for (var i = 0; i < entries.Length; i++) + writer.WriteLine(i < entries.Length - 1 ? $"{entries[i]}," : entries[i]); writer.DecreaseIndent(); - if (parentClass.StartBlock.Inherits != null) - writer.WriteLine("})"); - else - writer.WriteLine("}"); + writer.WriteLine(inherits ? ")" : "}"); } private static void WriteDeserializerBodyForUnionModel(CodeClass parentClass, LanguageWriter writer) { @@ -471,7 +472,7 @@ private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requ if (codeElement.ErrorMappings.Any()) { errorMappingVarName = "error_mapping"; - writer.WriteLine($"{errorMappingVarName} = Hash.new"); + writer.WriteLine($"{errorMappingVarName} = {{}}"); foreach (var errorMapping in codeElement.ErrorMappings) { writer.WriteLine($"{errorMappingVarName}[\"{errorMapping.Key.ToUpperInvariant()}\"] = {getDeserializationLambda(errorMapping.Value)}"); @@ -685,8 +686,8 @@ private string GetDeserializationMethodName(CodeTypeBase propType) private string getDeserializationLambda(CodeTypeBase targetTypeBase) { if (targetTypeBase is not CodeType targetType) - return "lambda {|pn| nil }"; - return $"lambda {{|pn| {conventions.GetQualifiedTypeName(targetType)}.create_from_discriminator_value(pn) }}"; + return "->(_pn) { nil }"; + return $"->(pn) {{ {conventions.GetQualifiedTypeName(targetType)}.create_from_discriminator_value(pn) }}"; } private static string TranslateObjectType(string typeName) { diff --git a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs index aced767e1f..d2aee3c3e3 100644 --- a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs +++ b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs @@ -232,7 +232,7 @@ public async Task CorrectsCoreTypesAsync() DefaultValue = "wrongDefaultValue" }).First(); await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); - Assert.Equal("Hash.new", property.DefaultValue); + Assert.Equal("{}", property.DefaultValue); } [Fact] public async Task EscapesReservedKeywordsAsync() diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeClassDeclarationWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeClassDeclarationWriterTests.cs index 0acd957036..60029f8a4e 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeClassDeclarationWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeClassDeclarationWriterTests.cs @@ -69,6 +69,17 @@ public void WritesImplementation() Assert.Contains("include", result); } [Fact] + public void WritesOneIncludePerMixinKeepingMethodLookupOrder() + { + var declaration = parentClass.StartBlock; + declaration.AddImplements(new CodeType { Name = "First" }, new CodeType { Name = "Second" }); + codeElementWriter.WriteCodeElement(declaration, writer); + var result = tw.ToString(); + // `include First, Second` looks methods up in First before Second, as does including Second then First + Assert.DoesNotContain(",", result.Split(Environment.NewLine).First(static x => x.Contains("include", StringComparison.Ordinal)), StringComparison.Ordinal); + Assert.True(result.IndexOf("include Second", StringComparison.Ordinal) < result.IndexOf("include First", StringComparison.Ordinal)); + } + [Fact] public void WritesInheritance() { var declaration = parentClass.StartBlock; diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs index 8d882000f6..8213721947 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs @@ -47,6 +47,7 @@ public void WritesEnum() Assert.Contains("= {", result); Assert.Contains(optionName, result); Assert.Contains("}.freeze", result); + Assert.DoesNotContain($"{optionName}: :{optionName},", result); AssertExtensions.CurlyBracesAreClosed(result); } [Fact] diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs index 9bf46df63c..c0de888733 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs @@ -336,10 +336,10 @@ public void WritesRequestExecutorBody() writer.Write(method); var result = tw.ToString(); Assert.Contains("request_info", result); - Assert.Contains("error_mapping = Hash.new", result); - Assert.Contains("error_mapping[\"4XX\"] = lambda {|pn| Error4XX.create_from_discriminator_value(pn) }", result); - Assert.Contains("error_mapping[\"5XX\"] = lambda {|pn| Error5XX.create_from_discriminator_value(pn) }", result); - Assert.Contains("error_mapping[\"401\"] = lambda {|pn| Error401.create_from_discriminator_value(pn) }", result); + Assert.Contains("error_mapping = {}", result); + Assert.Contains("error_mapping[\"4XX\"] = ->(pn) { Error4XX.create_from_discriminator_value(pn) }", result); + Assert.Contains("error_mapping[\"5XX\"] = ->(pn) { Error5XX.create_from_discriminator_value(pn) }", result); + Assert.Contains("error_mapping[\"401\"] = ->(pn) { Error401.create_from_discriminator_value(pn) }", result); Assert.Contains("send_async", result); AssertExtensions.CurlyBracesAreClosed(result); } @@ -729,7 +729,8 @@ public void WritesInheritedDeSerializerBody() AddSerializationProperties(); writer.Write(method); var result = tw.ToString(); - Assert.Contains("super.merge({", result); + Assert.Contains("super.merge(", result); + Assert.DoesNotContain("lambda", result); Assert.DoesNotContain("definedInParent", result, StringComparison.OrdinalIgnoreCase); AssertExtensions.CurlyBracesAreClosed(result); } @@ -791,7 +792,7 @@ public void EscapesWireNamesInSerializerAndDeserializerBody() method.Kind = CodeMethodKind.Deserializer; writer.Write(method); var deserializerResult = tw.ToString(); - Assert.Contains("\"line1\\\"\\#\\nbreak\" => lambda", deserializerResult); + Assert.Contains("\"line1\\\"\\#\\nbreak\" => ->(n)", deserializerResult); } [Fact] public void WritesTranslatedTypesDeSerializerBody() From ee9f41083b0f7bbf00a8c978f2e50d0bdfb75c11 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 12:19:31 +0100 Subject: [PATCH 10/25] style(ruby): drop empty parentheses from method definitions and calls - spaces around parameter defaults, and no redundant self on the request generator call --- it/ruby/.rubocop.yml | 12 ------- it/ruby/spec/basic/integration_test_basic.rb | 2 +- .../integration_test_defaultvalues.rb | 32 +++++++++---------- .../Writers/Ruby/CodeMethodWriter.cs | 31 ++++++++---------- .../Writers/Ruby/CodePropertyWriter.cs | 2 +- .../Writers/Ruby/RubyConventionService.cs | 2 +- .../Writers/Ruby/CodeMethodWriterTests.cs | 11 ++++--- 7 files changed, 39 insertions(+), 53 deletions(-) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index d6f55d74b5..be052dfbb4 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -11,9 +11,6 @@ Style/StringLiteralsInInterpolation: Layout/LineLength: Enabled: false -Style/DefWithParentheses: - Enabled: false - Style/RedundantReturn: Enabled: false @@ -32,21 +29,12 @@ Style/FrozenStringLiteralComment: Layout/EmptyLineAfterGuardClause: Enabled: false -Style/MethodCallWithoutArgsParentheses: - Enabled: false - Naming/ClassAndModuleCamelCase: Enabled: false Naming/AccessorMethodName: Enabled: false -Layout/SpaceAroundEqualsInParameterDefault: - Enabled: false - -Style/RedundantSelf: - Enabled: false - Lint/EmptyFile: Enabled: false diff --git a/it/ruby/spec/basic/integration_test_basic.rb b/it/ruby/spec/basic/integration_test_basic.rb index 56497f1fb6..65900bf4be 100644 --- a/it/ruby/spec/basic/integration_test_basic.rb +++ b/it/ruby/spec/basic/integration_test_basic.rb @@ -2,7 +2,7 @@ RSpec.describe Integration_test do it "does something useful" do - auth_provider = MicrosoftKiotaAbstractions::AnonymousAuthenticationProvider.new() + auth_provider = MicrosoftKiotaAbstractions::AnonymousAuthenticationProvider.new request_adapter = MicrosoftKiotaFaraday::FaradayRequestAdapter.new(auth_provider) request_adapter.set_base_url('http://127.0.0.1:1080') client = Integration_test::Client::ApiClient.new(request_adapter) diff --git a/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb b/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb index ce77368990..00744c154f 100644 --- a/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb +++ b/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb @@ -2,12 +2,12 @@ RSpec.describe Integration_test do it "test default value initialization of model class" do - auth_provider = MicrosoftKiotaAbstractions::AnonymousAuthenticationProvider.new() + auth_provider = MicrosoftKiotaAbstractions::AnonymousAuthenticationProvider.new request_adapter = MicrosoftKiotaFaraday::FaradayRequestAdapter.new(auth_provider) request_adapter.set_base_url('http://127.0.0.1:1080') client = Integration_test::Client::ApiClient.new(request_adapter) - service_response = client.api().v1().weather_forecast().get().resume + service_response = client.api.v1.weather_forecast.get.resume # Here, a single object is returned instead of a list. So we just check for null expect(service_response).to_not be nil @@ -15,29 +15,29 @@ # pp service_response.enum_value().class # Now the real test: create a model class and verify that all properties have the default values. - model = Integration_test::Client::Models::WeatherForecast.new() + model = Integration_test::Client::Models::WeatherForecast.new - expect(model.bool_value()).to be true + expect(model.bool_value).to be true expect(model.date_only_value).to_not be nil - expect(model.date_only_value.to_s()).to eq("1900-01-01") + expect(model.date_only_value.to_s).to eq("1900-01-01") expect(model.date_value).to_not be nil - expect(model.date_value.to_s()).to eq("1900-01-01T00:00:00+00:00") + expect(model.date_value.to_s).to eq("1900-01-01T00:00:00+00:00") - expect(model.decimal_value()).to be 25.5 - expect(model.double_value()).to be 25.5 - expect(model.enum_value()).to be Integration_test::Client::Models::WeatherForecastEnumValue[:One] - expect(model.float_value()).to be 25.5 + expect(model.decimal_value).to be 25.5 + expect(model.double_value).to be 25.5 + expect(model.enum_value).to be Integration_test::Client::Models::WeatherForecastEnumValue[:One] + expect(model.float_value).to be 25.5 expect(model.guid_value).to_not be nil - expect(model.guid_value().to_s()).to eq("00000000-0000-0000-0000-000000000000") + expect(model.guid_value.to_s).to eq("00000000-0000-0000-0000-000000000000") - expect(model.long_value()).to be 255 - expect(model.summary()).to eq("Test") - expect(model.temperature_c()).to be 15 + expect(model.long_value).to be 255 + expect(model.summary).to eq("Test") + expect(model.temperature_c).to be 15 - expect(model.time_value()).to_not be nil - expect(model.time_value().strftime("%H:%M:%S")).to eq("00:00:00") + expect(model.time_value).to_not be nil + expect(model.time_value.strftime("%H:%M:%S")).to eq("00:00:00") end end diff --git a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs index 9043f04459..3b7bc0a8dd 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs @@ -419,7 +419,7 @@ private static void WriteDeserializerBodyForUnionModel(CodeClass parentClass, La foreach (var property in complexProperties) { writer.StartBlock($"unless @{property.Name.ToSnakeCase()}.nil?"); - writer.WriteLine($"return @{property.Name.ToSnakeCase()}.get_field_deserializers()"); + writer.WriteLine($"return @{property.Name.ToSnakeCase()}.get_field_deserializers"); writer.CloseBlock("end"); } writer.WriteLine("return {}"); @@ -454,18 +454,13 @@ private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requ .FirstOrDefault(x => x.IsOfKind(CodeMethodKind.RequestGenerator) && x.HttpMethod == codeElement.HttpMethod) ?.Name ?.ToSnakeCase(); - writer.WriteLine($"request_info = self.{generatorMethodName}("); var requestInfoParameters = new CodeParameter?[] { requestParams.requestBody, requestParams.requestContentType, requestParams.requestConfiguration } .OfType() .Select(static x => x.Name.ToSnakeCase()) .ToArray(); - if (requestInfoParameters.Length != 0) - { - writer.IncreaseIndent(); - writer.WriteLine(requestInfoParameters.Aggregate(static (x, y) => $"{x}, {y}")); - writer.DecreaseIndent(); - } - writer.WriteLine(")"); + writer.WriteLine(requestInfoParameters.Length == 0 ? + $"request_info = {generatorMethodName}" : + $"request_info = {generatorMethodName}({string.Join(", ", requestInfoParameters)})"); var isStream = conventions.StreamTypeName.Equals(returnType, StringComparison.OrdinalIgnoreCase); var genericTypeForSendMethod = GetSendRequestMethodName(isStream); var errorMappingVarName = "nil"; @@ -485,7 +480,7 @@ private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams req { if (codeElement.HttpMethod == null) throw new InvalidOperationException("http method cannot be null"); - writer.WriteLine("request_info = MicrosoftKiotaAbstractions::RequestInformation.new()"); + writer.WriteLine("request_info = MicrosoftKiotaAbstractions::RequestInformation.new"); if (requestParams.requestConfiguration != null) { var queryString = requestParams.QueryParameters; @@ -630,8 +625,8 @@ private void WriteMethodPrototype(CodeMethod code, LanguageWriter writer) .Select(p => conventions.GetParameterSignature(p, code).ToSnakeCase()) .ToList()); var staticPrefix = code.IsStatic ? "self." : string.Empty; - var openParenthesis = code.IsOfKind(CodeMethodKind.Getter) ? string.Empty : "("; - var closeParenthesis = code.IsOfKind(CodeMethodKind.Getter) ? string.Empty : ")"; + var openParenthesis = parameters.Length == 0 ? string.Empty : "("; + var closeParenthesis = parameters.Length == 0 ? string.Empty : ")"; var equalsSign = code.IsOfKind(CodeMethodKind.Setter) ? "=" : string.Empty; writer.StartBlock($"def {staticPrefix}{methodName.ToSnakeCase()}{equalsSign}{openParenthesis}{parameters}{closeParenthesis}"); } @@ -674,12 +669,12 @@ private string GetDeserializationMethodName(CodeTypeBase propType) } return propertyType switch { - "string" or "boolean" or "number" or "float" or "Guid" => $"get_{propertyType.ToSnakeCase()}_value()", - "binary" or "Binary" or "base64" or "base64url" => "get_string_value()", //TODO: add support for binary - "DateTimeOffset" or "DateTime" => "get_date_time_value()", - "TimeSpan" or "MicrosoftKiotaAbstractions::ISODuration" => "get_duration_value()", - "DateOnly" or "Date" => "get_date_value()", - "TimeOnly" or "Time" => "get_time_value()", + "string" or "boolean" or "number" or "float" or "Guid" => $"get_{propertyType.ToSnakeCase()}_value", + "binary" or "Binary" or "base64" or "base64url" => "get_string_value", //TODO: add support for binary + "DateTimeOffset" or "DateTime" => "get_date_time_value", + "TimeSpan" or "MicrosoftKiotaAbstractions::ISODuration" => "get_duration_value", + "DateOnly" or "Date" => "get_date_value", + "TimeOnly" or "Time" => "get_time_value", _ => $"get_object_value({getDeserializationLambda(propType)})", }; } diff --git a/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs index 8caf13f5d3..d9e005cd14 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs @@ -17,7 +17,7 @@ public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter w switch (codeElement.Kind) { case CodePropertyKind.RequestBuilder: - writer.WriteLine($"def {codeElement.Name.ToSnakeCase()}()"); + writer.WriteLine($"def {codeElement.Name.ToSnakeCase()}"); writer.IncreaseIndent(); conventions.AddRequestBuilderBody(parentClass, conventions.GetQualifiedTypeName(codeElement.Type), writer, prefix: "return "); writer.DecreaseIndent(); diff --git a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs index 69bf9ac697..91a1f58e4e 100644 --- a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs +++ b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs @@ -53,7 +53,7 @@ public override string GetParameterSignature(CodeParameter parameter, CodeElemen { ArgumentNullException.ThrowIfNull(parameter); var defaultValue = parameter.Optional && (targetElement is not CodeMethod currentMethod || !currentMethod.IsOfKind(CodeMethodKind.Setter)) ? - $"={(string.IsNullOrEmpty(parameter.DefaultValue) ? "nil" : SanitizeRubyDoubleQuoteLiteral(parameter.DefaultValue))}" : + $" = {(string.IsNullOrEmpty(parameter.DefaultValue) ? "nil" : SanitizeRubyDoubleQuoteLiteral(parameter.DefaultValue))}" : string.Empty; return $"{parameter.Name}{defaultValue}"; } diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs index c0de888733..f33c0d5c62 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs @@ -631,7 +631,8 @@ public void WritesRequestGeneratorBody() AddRequestBodyParameters(); writer.Write(method); var result = tw.ToString(); - Assert.Contains("request_info = MicrosoftKiotaAbstractions::RequestInformation.new()", result); + Assert.Contains("request_info = MicrosoftKiotaAbstractions::RequestInformation.new", result); + Assert.DoesNotContain("RequestInformation.new()", result); Assert.Contains("request_info.path_parameters", result); Assert.Contains("request_info.url_template", result); Assert.Contains("http_method = :GET", result); @@ -1122,7 +1123,7 @@ public void EscapesParameterDefaultsInSignature() }); writer.Write(method); var result = tw.ToString(); - Assert.Contains("def initialize(display_name=\"\\#{`id`}\")", result); + Assert.Contains("def initialize(display_name = \"\\#{`id`}\")", result); } [Fact] public void WritesConstructorWithDefaultValuesThatRequireParsing() @@ -1298,7 +1299,8 @@ public void DoesNotWriteConstructorWithDefaultFromComposedType() writer.Write(method); var result = tw.ToString(); - Assert.Contains("initialize()", result); + Assert.Contains("def initialize", result); + Assert.DoesNotContain("initialize()", result); Assert.DoesNotContain(defaultValue, result);//ensure the composed type is not referenced } [Fact] @@ -1905,7 +1907,8 @@ public void WritesUnionDeserializerBody() writer.Write(method); var result = tw.ToString(); Assert.DoesNotContain("super", result); - Assert.Contains("@complex_type1_value.get_field_deserializers()", result); + Assert.Contains("@complex_type1_value.get_field_deserializers", result); + Assert.DoesNotContain("get_field_deserializers()", result); Assert.DoesNotContain("complex_type2_value", result); Assert.Contains("return {}", result); AssertBalancedBlocks(result); From c94498650cdbc9c034ed2c2df9f05ce2fb4c877f Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 12:27:33 +0100 Subject: [PATCH 11/25] style(ruby): double quote every generated string literal --- CHANGELOG.md | 1 + it/ruby/.rubocop.yml | 2 +- it/ruby/spec/basic/integration_test_basic.rb | 2 +- .../integration_test_defaultvalues.rb | 2 +- .../Ruby/CodeClassDeclarationWriter.cs | 4 +-- .../Writers/Ruby/CodeMethodWriter.cs | 22 +++++++-------- .../Writers/Ruby/CodeNamespaceWriter.cs | 2 +- .../Writers/Ruby/RubyConventionService.cs | 5 +++- .../Writers/Ruby/CodeMethodWriterTests.cs | 28 +++++++++++++------ .../Writers/Ruby/CodeNamespaceWriterTests.cs | 6 ++-- 10 files changed, 45 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eac7aaa93f..113fcf229f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Preserve models for multipart properties with default content types when other properties specify an encoding. [#7342](https://github.com/microsoft/kiota/issues/7342) - Dart: escape enum options named value or values to avoid conflicts with generated and built-in enum members. [#7807](https://github.com/microsoft/kiota/issues/7807) +- Ruby: generated string literals are double quoted, so a base URL, URL template or content type containing a newline or tab now keeps it instead of a literal backslash sequence. - Ruby: namespaces with nothing to autoload no longer get an empty barrel file, and generated files no longer require them (561 fewer files in a GitHub client). - Ruby: a client generated with a multi-segment `--namespace-name`, such as `integration_test.client`, failed to load because its root file was written one directory too deep. - Ruby: namespace barrels register their models and enums with `autoload` instead of requiring them, so a subclass no longer fails to load when its base class file is required first. Other files require the barrel rather than an individual model file, and models now load on first use. [#7956](https://github.com/microsoft/kiota/issues/7956) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index be052dfbb4..883b187efc 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -2,7 +2,7 @@ AllCops: TargetRubyVersion: 3.2 Style/StringLiterals: - Enabled: false + EnforcedStyle: double_quotes Style/StringLiteralsInInterpolation: Enabled: true diff --git a/it/ruby/spec/basic/integration_test_basic.rb b/it/ruby/spec/basic/integration_test_basic.rb index 65900bf4be..9bc5d48d02 100644 --- a/it/ruby/spec/basic/integration_test_basic.rb +++ b/it/ruby/spec/basic/integration_test_basic.rb @@ -4,7 +4,7 @@ it "does something useful" do auth_provider = MicrosoftKiotaAbstractions::AnonymousAuthenticationProvider.new request_adapter = MicrosoftKiotaFaraday::FaradayRequestAdapter.new(auth_provider) - request_adapter.set_base_url('http://127.0.0.1:1080') + request_adapter.set_base_url("http://127.0.0.1:1080") client = Integration_test::Client::ApiClient.new(request_adapter) expect(client).to_not be nil diff --git a/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb b/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb index 00744c154f..b130ea3edc 100644 --- a/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb +++ b/it/ruby/spec/defaultvalues/integration_test_defaultvalues.rb @@ -4,7 +4,7 @@ it "test default value initialization of model class" do auth_provider = MicrosoftKiotaAbstractions::AnonymousAuthenticationProvider.new request_adapter = MicrosoftKiotaFaraday::FaradayRequestAdapter.new(auth_provider) - request_adapter.set_base_url('http://127.0.0.1:1080') + request_adapter.set_base_url("http://127.0.0.1:1080") client = Integration_test::Client::ApiClient.new(request_adapter) service_response = client.api.v1.weather_forecast.get.resume diff --git a/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs index ffb3b85894..4ae8a88198 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs @@ -34,7 +34,7 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit .GroupBy(static x => x) .Select(static x => x.Key) .Order(StringComparer.OrdinalIgnoreCase)) - writer.WriteLine($"require '{codeUsing}'"); + writer.WriteLine($"require {RubyConventionService.ToRubyStringLiteral(codeUsing)}"); foreach (var relativePath in codeElement.Usings .Where(static x => !x.IsExternal) @@ -45,7 +45,7 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit .Select(static x => x.Item3) .Distinct() .Order(StringComparer.OrdinalIgnoreCase)) - writer.WriteLine($"require_relative '{relativePath.ToSnakeCase()}'"); + writer.WriteLine($"require_relative {RubyConventionService.ToRubyStringLiteral(relativePath.ToSnakeCase())}"); } writer.WriteLine(); if (codeElement.Parent?.Parent is CodeNamespace ns) diff --git a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs index 3b7bc0a8dd..5b64e3c9ff 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs @@ -227,7 +227,7 @@ private static void AddNullChecks(CodeMethod codeElement, LanguageWriter writer) .Where(static x => !x.Optional && !x.IsOfKind(CodeParameterKind.PathParameters, CodeParameterKind.RequestAdapter)) .Select(static x => x.Name.ToSnakeCase()) .OrderBy(static x => x)) - writer.WriteLine($"raise StandardError, '{parameter} cannot be null' if {parameter}.nil?"); + writer.WriteLine($"raise StandardError, {RubyConventionService.ToRubyStringLiteral($"{parameter} cannot be null")} if {parameter}.nil?"); } private static void WriteQueryParametersMapper(CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer) { @@ -238,7 +238,7 @@ private static void WriteQueryParametersMapper(CodeMethod codeElement, CodeClass var escapedProperties = parentClass.Properties.Where(static x => x.IsOfKind(CodePropertyKind.QueryParameter) && x.IsNameEscaped); foreach (var escapedProperty in escapedProperties) { - writer.StartBlock($"when \"{escapedProperty.Name}\""); + writer.StartBlock($"when {RubyConventionService.ToRubyStringLiteral(escapedProperty.Name)}"); writer.WriteLine($"return \"{RubyConventionService.SanitizeRubyDoubleQuoteLiteral(escapedProperty.SerializationName)}\""); writer.DecreaseIndent(); } @@ -262,10 +262,10 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me if (!string.IsNullOrEmpty(method.BaseUrl)) { writer.StartBlock($"if @{requestAdapterPropertyName}.get_base_url.nil? || @{requestAdapterPropertyName}.get_base_url.empty?"); - writer.WriteLine($"@{requestAdapterPropertyName}.set_base_url('{method.BaseUrl.SanitizeSingleQuote()}')"); + writer.WriteLine($"@{requestAdapterPropertyName}.set_base_url({RubyConventionService.ToRubyStringLiteral(method.BaseUrl)})"); writer.CloseBlock("end"); if (pathParametersProperty != null) - writer.WriteLine($"@{pathParametersProperty.Name.ToSnakeCase()}['baseurl'] = @{requestAdapterPropertyName}.get_base_url"); + writer.WriteLine($"@{pathParametersProperty.Name.ToSnakeCase()}[\"baseurl\"] = @{requestAdapterPropertyName}.get_base_url"); } } private static void WriteSerializationRegistration(CodeClass parentClass, HashSet serializationClassNames, LanguageWriter writer, string methodName) @@ -500,28 +500,28 @@ private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams req } if (requestParams.requestBody != null) { - var sanitizedRequestBodyContentType = codeElement.RequestBodyContentType.SanitizeSingleQuote(); + var requestBodyContentType = RubyConventionService.ToRubyStringLiteral(codeElement.RequestBodyContentType); if (requestParams.requestBody.Type.Name.Equals(conventions.StreamTypeName, StringComparison.OrdinalIgnoreCase)) { if (requestParams.requestContentType is not null) writer.WriteLine($"request_info.set_stream_content({requestParams.requestBody.Name}, {requestParams.requestContentType.Name})"); - else if (!string.IsNullOrEmpty(sanitizedRequestBodyContentType)) - writer.WriteLine($"request_info.set_stream_content({requestParams.requestBody.Name}, '{sanitizedRequestBodyContentType}')"); + else if (!string.IsNullOrEmpty(codeElement.RequestBodyContentType)) + writer.WriteLine($"request_info.set_stream_content({requestParams.requestBody.Name}, {requestBodyContentType})"); } else if (parentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter) is CodeProperty requestAdapterProperty) - writer.WriteLine($"request_info.set_content_from_parsable(@{requestAdapterProperty.Name.ToSnakeCase()}, '{sanitizedRequestBodyContentType}', {requestParams.requestBody.Name})"); + writer.WriteLine($"request_info.set_content_from_parsable(@{requestAdapterProperty.Name.ToSnakeCase()}, {requestBodyContentType}, {requestParams.requestBody.Name})"); } } if (parentClass.GetPropertyOfKind(CodePropertyKind.PathParameters) is CodeProperty urlTemplateParamsProperty && parentClass.GetPropertyOfKind(CodePropertyKind.UrlTemplate) is CodeProperty urlTemplateProperty) { - var urlTemplateValue = codeElement.HasUrlTemplateOverride ? $"'{codeElement.UrlTemplateOverride.SanitizeSingleQuote()}'" : GetPropertyCall(urlTemplateProperty, "''"); + var urlTemplateValue = codeElement.HasUrlTemplateOverride ? RubyConventionService.ToRubyStringLiteral(codeElement.UrlTemplateOverride) : GetPropertyCall(urlTemplateProperty, "\"\""); writer.WriteLines($"request_info.url_template = {urlTemplateValue}", - $"request_info.path_parameters = {GetPropertyCall(urlTemplateParamsProperty, "''")}"); + $"request_info.path_parameters = {GetPropertyCall(urlTemplateParamsProperty, "\"\"")}"); } writer.WriteLine($"request_info.http_method = :{codeElement.HttpMethod.Value.ToString().ToUpperInvariant()}"); if (codeElement.ShouldAddAcceptHeader) - writer.WriteLine($"request_info.headers.try_add('Accept', '{codeElement.AcceptHeaderValue.SanitizeSingleQuote()}')"); + writer.WriteLine($"request_info.headers.try_add(\"Accept\", {RubyConventionService.ToRubyStringLiteral(codeElement.AcceptHeaderValue)})"); writer.WriteLine("return request_info"); } private static string GetPropertyCall(CodeProperty property, string defaultValue) => property == null ? defaultValue : $"@{property.NamePrefix}{property.Name.ToSnakeCase()}"; diff --git a/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs index 2849830cba..8f555a3cbd 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs @@ -30,7 +30,7 @@ public override void WriteCodeElement(CodeNamespace codeElement, LanguageWriter if (autoloaded.Count == 0) return; conventions.WriteNamespaceModules(codeElement, writer); foreach (var element in autoloaded) - writer.WriteLine($"autoload :{element.Name.ToFirstCharacterUpperCase()}, ::File.expand_path('{PathSegmenter.GetRelativeFileName(codeElement, element).ToSnakeCase()}', __dir__)"); + writer.WriteLine($"autoload :{element.Name.ToFirstCharacterUpperCase()}, ::File.expand_path({RubyConventionService.ToRubyStringLiteral(PathSegmenter.GetRelativeFileName(codeElement, element).ToSnakeCase())}, __dir__)"); conventions.WriteNamespaceClosing(codeElement, writer); } } diff --git a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs index 91a1f58e4e..b0fdc43320 100644 --- a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs +++ b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs @@ -25,6 +25,9 @@ public class RubyConventionService : CommonLanguageConventionService // a barrel is written, and required, only when it has something to autoload internal static bool HasAutoloadedMembers(CodeNamespace codeNamespace) => codeNamespace.Classes.Any(IsAutoloaded) || codeNamespace.Enums.Any(IsAutoloaded); + // double quotes are the only Ruby quoting in which the shared escapes such as \n and \t mean what they say + internal static string ToRubyStringLiteral(string? value) => + $"\"{(value ?? string.Empty).SanitizeDoubleQuote().Replace("#", "\\#", StringComparison.Ordinal)}\""; internal static string SanitizeRubyDoubleQuoteLiteral(string? value) { if (string.IsNullOrEmpty(value)) return string.Empty; @@ -35,7 +38,7 @@ internal static string SanitizeRubyDoubleQuoteLiteral(string? value) return $"\"{value[1..^1].SanitizeDoubleQuote().Replace("#", "\\#", StringComparison.Ordinal)}\""; if (value[0] == '\'' && value[^1] == '\'') - return $"'{value[1..^1].SanitizeSingleQuote().Replace("#", "\\#", StringComparison.Ordinal)}'"; + return ToRubyStringLiteral(value[1..^1]); } return value.SanitizeDoubleQuote().Replace("#", "\\#", StringComparison.Ordinal); diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs index f33c0d5c62..a441fef0c7 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs @@ -636,7 +636,7 @@ public void WritesRequestGeneratorBody() Assert.Contains("request_info.path_parameters", result); Assert.Contains("request_info.url_template", result); Assert.Contains("http_method = :GET", result); - Assert.Contains("request_info.headers.try_add('Accept', 'application/json')", result); + Assert.Contains("request_info.headers.try_add(\"Accept\", \"application/json\")", result); Assert.Contains("set_query_string_parameters_from_raw_object", result); Assert.Contains("add_headers_from_raw_object", result); Assert.Contains("add_request_options", result); @@ -655,7 +655,7 @@ public void WritesRequestGeneratorBodyWhenUrlTemplateIsOverrode() method.UrlTemplateOverride = "{baseurl+}/foo/bar"; writer.Write(method); var result = tw.ToString(); - Assert.Contains("request_info.url_template = '{baseurl+}/foo/bar'", result); + Assert.Contains("request_info.url_template = \"{baseurl+}/foo/bar\"", result); } [Fact] public void EscapesRequestGeneratorBodyWhenUrlTemplateIsOverrode() @@ -669,7 +669,7 @@ public void EscapesRequestGeneratorBodyWhenUrlTemplateIsOverrode() method.UrlTemplateOverride = "{baseurl+}/foo/'bar\nbaz"; writer.Write(method); var result = tw.ToString(); - Assert.Contains("request_info.url_template = '{baseurl+}/foo/\\'bar\\nbaz'", result); + Assert.Contains("request_info.url_template = \"{baseurl+}/foo/'bar\\nbaz\"", result); } [Fact] public void WritesRequestGeneratorBodyKnownRequestBodyType() @@ -1338,8 +1338,8 @@ public void WritesApiConstructor() writer.Write(method); var result = tw.ToString(); Assert.Contains(coreProp.Name, result); - Assert.Contains($"['baseurl'] = @core.get_base_url", result); - Assert.Contains($"set_base_url('{method.BaseUrl}')", result); + Assert.Contains($"[\"baseurl\"] = @core.get_base_url", result); + Assert.Contains($"set_base_url(\"{method.BaseUrl}\")", result); } [Fact] public void EscapesApiConstructorBaseUrl() @@ -1375,7 +1375,7 @@ public void EscapesApiConstructorBaseUrl() }); writer.Write(method); var result = tw.ToString(); - Assert.Contains("set_base_url('https://graph.microsoft.com/v1.0/\\'evil\\npath')", result); + Assert.Contains("set_base_url(\"https://graph.microsoft.com/v1.0/'evil\\npath\")", result); } [Fact] public void WritesApiConstructorWithBackingStore() @@ -1565,9 +1565,21 @@ public void WritesRequestGeneratorAcceptHeaderQuotes() method.AcceptedResponseTypes.Add("application/json; profile='CamelCase'"); writer.Write(method); var result = tw.ToString(); - Assert.Contains("request_info.headers.try_add('Accept', 'application/json; profile=\\'CamelCase\\'')", result); + Assert.Contains("request_info.headers.try_add(\"Accept\", \"application/json; profile='CamelCase'\")", result); } + [Fact] + public void WritesLiteralsThatCannotInterpolate() + { + setup(); + method.Kind = CodeMethodKind.RequestGenerator; + method.HttpMethod = HttpMethod.Get; + AddRequestProperties(); + method.AcceptedResponseTypes.Add("text/#{`id`}"); + writer.Write(method); + var result = tw.ToString(); + Assert.Contains("try_add(\"Accept\", \"text/\\#{`id`}\")", result); + } [Fact] public void WritesRequestGeneratorContentTypeQuotes() { @@ -1579,7 +1591,7 @@ public void WritesRequestGeneratorContentTypeQuotes() method.RequestBodyContentType = "application/json; profile='CamelCase'"; writer.Write(method); var result = tw.ToString(); - Assert.Contains("'application/json; profile=\\'CamelCase\\''", result); + Assert.Contains("\"application/json; profile='CamelCase'\"", result); } private void AddUnionTypeWrapper() { diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs index de47902a5b..d70cd4bacc 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs @@ -46,9 +46,9 @@ public void RegistersModelsAndEnumsForAutoloadInsteadOfRequiringThem() Assert.DoesNotContain("require", result, StringComparison.Ordinal); Assert.Contains("module Graph", result, StringComparison.Ordinal); Assert.Contains("module Models", result, StringComparison.Ordinal); - Assert.Contains("autoload :Animal, ::File.expand_path('animal', __dir__)", result, StringComparison.Ordinal); - Assert.Contains("autoload :Cat, ::File.expand_path('cat', __dir__)", result, StringComparison.Ordinal); - Assert.Contains("autoload :Color, ::File.expand_path('color', __dir__)", result, StringComparison.Ordinal); + Assert.Contains("autoload :Animal, ::File.expand_path(\"animal\", __dir__)", result, StringComparison.Ordinal); + Assert.Contains("autoload :Cat, ::File.expand_path(\"cat\", __dir__)", result, StringComparison.Ordinal); + Assert.Contains("autoload :Color, ::File.expand_path(\"color\", __dir__)", result, StringComparison.Ordinal); } [Fact] public void DoesNotRegisterAnEnumWithoutOptions() From cb6adb174799fb5db1174414bc9290e64b341d18 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 12:34:29 +0100 Subject: [PATCH 12/25] style(ruby): separate class members with one blank line - track in the language writer whether a block has just opened, so no blank line starts a class body --- it/ruby/.rubocop.yml | 3 --- src/Kiota.Builder/Writers/LanguageWriter.cs | 13 +++++++++++++ .../Writers/Ruby/CodeClassDeclarationWriter.cs | 5 ++++- src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs | 3 +-- .../Writers/Ruby/CodePropertyWriter.cs | 5 +---- .../Writers/Ruby/RubyConventionService.cs | 6 ++++++ .../Writers/Ruby/CodePropertyWriterTests.cs | 13 +++++++++++++ 7 files changed, 38 insertions(+), 10 deletions(-) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index 883b187efc..fa37f5d764 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -17,9 +17,6 @@ Style/RedundantReturn: Style/IfUnlessModifier: Enabled: false -Layout/EmptyLineBetweenDefs: - Enabled: false - Style/Documentation: Enabled: false diff --git a/src/Kiota.Builder/Writers/LanguageWriter.cs b/src/Kiota.Builder/Writers/LanguageWriter.cs index 7baa143624..70e25dac0c 100644 --- a/src/Kiota.Builder/Writers/LanguageWriter.cs +++ b/src/Kiota.Builder/Writers/LanguageWriter.cs @@ -76,6 +76,15 @@ public static string NewLine internal void WriteLine(string line, bool includeIndent = true) { writer?.WriteLine(includeIndent ? GetIndent() + line : line); + IsAtBlockStart = false; + } + /// + /// Whether nothing has been written since the last block was opened, so a writer can separate + /// sibling members without putting a blank line at the start of a block. + /// + internal bool IsAtBlockStart + { + get; private set; } internal void WriteLines(IEnumerable lines) { @@ -97,6 +106,7 @@ internal void StartBlock(string symbol = "{", bool increaseIndent = true) WriteLine(symbol); if (increaseIndent) IncreaseIndent(); + IsAtBlockStart = true; } internal void CloseBlock(string symbol = "}", bool decreaseIndent = true) { @@ -115,6 +125,7 @@ internal void WriteBlock(string startSymbol = "{", string closeSymbol = "}", par internal void Write(string text, bool includeIndent = true) { writer?.Write(includeIndent ? GetIndent() + text : text); + IsAtBlockStart = false; } /// /// Runs against a temporary buffer and returns the lines it produced @@ -127,6 +138,7 @@ internal IReadOnlyList CaptureLines(Action write) { ArgumentNullException.ThrowIfNull(write); var previousWriter = writer; + var previousIsAtBlockStart = IsAtBlockStart; using var buffer = new StringWriter(); writer = buffer; try @@ -136,6 +148,7 @@ internal IReadOnlyList CaptureLines(Action write) finally { writer = previousWriter; + IsAtBlockStart = previousIsAtBlockStart; } var lines = buffer.GetStringBuilder().ToString().Split(buffer.NewLine); // WriteLine terminates every line, so a trailing separator is not an extra empty line diff --git a/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs index 4ae8a88198..19b6220a3e 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs @@ -47,7 +47,10 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit .Order(StringComparer.OrdinalIgnoreCase)) writer.WriteLine($"require_relative {RubyConventionService.ToRubyStringLiteral(relativePath.ToSnakeCase())}"); } - writer.WriteLine(); + if (codeElement.Parent?.Parent is CodeClass) + RubyConventionService.WriteMemberSeparator(writer); + else + writer.WriteLine(); if (codeElement.Parent?.Parent is CodeNamespace ns) { conventions.WriteNamespaceModules(ns, writer); diff --git a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs index 5b64e3c9ff..23d90d762d 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs @@ -18,8 +18,7 @@ public override void WriteCodeElement(CodeMethod codeElement, LanguageWriter wri ArgumentNullException.ThrowIfNull(writer); if (codeElement.Parent is not CodeClass parentClass) throw new InvalidOperationException("the parent of a method should be a class"); var returnType = conventions.GetTypeString(codeElement.ReturnType, codeElement); - if (parentClass.Properties.Any(static x => x.IsOfKind(CodePropertyKind.QueryParameter, CodePropertyKind.QueryParameters, CodePropertyKind.Headers, CodePropertyKind.Options))) - writer.WriteLine(); + RubyConventionService.WriteMemberSeparator(writer); WriteMethodDocumentation(codeElement, writer); var inherits = parentClass.StartBlock.Inherits != null; var requestBodyParam = codeElement.Parameters.OfKind(CodeParameterKind.RequestBody); diff --git a/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs index d9e005cd14..9111af5c36 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs @@ -12,6 +12,7 @@ public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter w ArgumentNullException.ThrowIfNull(codeElement); ArgumentNullException.ThrowIfNull(writer); if (codeElement.ExistsInExternalBaseType) return; + RubyConventionService.WriteMemberSeparator(writer); conventions.WriteShortDescription(codeElement, writer); if (codeElement.Parent is not CodeClass parentClass) throw new InvalidOperationException("The parent of a property should be a class"); switch (codeElement.Kind) @@ -27,14 +28,10 @@ public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter w case CodePropertyKind.QueryParameters: case CodePropertyKind.Headers: case CodePropertyKind.Options: - writer.WriteLine($"attr_accessor :{codeElement.Name.ToSnakeCase()}"); - break; case CodePropertyKind.Custom: case CodePropertyKind.AdditionalData: case CodePropertyKind.BackingStore: - // a model always has methods after its properties, so this never precedes the class end writer.WriteLine($"attr_accessor :{codeElement.Name.ToSnakeCase()}"); - writer.WriteLine(); break; default: writer.WriteLine($"@{codeElement.NamePrefix}{codeElement.Name.ToSnakeCase()}"); diff --git a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs index b0fdc43320..8c689e7314 100644 --- a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs +++ b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs @@ -22,6 +22,12 @@ public class RubyConventionService : CommonLanguageConventionService CodeEnum codeEnum => codeEnum.Parent is CodeNamespace ns && !ns.HasClassNamedAfterItself() && codeEnum.Options.Any(), _ => false, }; + // one blank line between class members, none at the start of a block + internal static void WriteMemberSeparator(LanguageWriter writer) + { + ArgumentNullException.ThrowIfNull(writer); + if (!writer.IsAtBlockStart) writer.WriteLine(); + } // a barrel is written, and required, only when it has something to autoload internal static bool HasAutoloadedMembers(CodeNamespace codeNamespace) => codeNamespace.Classes.Any(IsAutoloaded) || codeNamespace.Enums.Any(IsAutoloaded); diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodePropertyWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodePropertyWriterTests.cs index 985e3f1840..45fd1af436 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodePropertyWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodePropertyWriterTests.cs @@ -129,6 +129,19 @@ public void WritesAccessedProperty() Assert.Contains($"attr_accessor :{PropertyName.ToSnakeCase()}", result); } [Fact] + public void SeparatesClassMembersWithOneBlankLineButNoneAtTheStartOfTheBody() + { + property.Kind = CodePropertyKind.Custom; + writer.StartBlock("class Sample"); + writer.Write(property); + writer.Write(property); + writer.CloseBlock("end"); + var lines = tw.ToString().TrimEnd().Split(Environment.NewLine); + Assert.NotEqual(string.Empty, lines[1].Trim()); + Assert.Single(lines, static x => x.Length == 0); + Assert.NotEqual(string.Empty, lines[^2].Trim()); + } + [Fact] public void WritesCustomProperty() { property.Kind = CodePropertyKind.Custom; From 299961e8775d591f2c8b206852e5c9bec2cc2b8f Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 12:48:58 +0100 Subject: [PATCH 13/25] style(ruby): end methods on their value instead of an explicit return - a blank line after guard clauses, and modifier if/unless for one-statement conditionals - composed-type factories with nothing to assign return the new instance directly --- it/ruby/.rubocop.yml | 9 - .../Writers/Ruby/CodeMethodWriter.cs | 166 +++++++++++------- .../Writers/Ruby/CodePropertyWriter.cs | 2 +- .../Writers/Ruby/CodeMethodWriterTests.cs | 39 ++-- 4 files changed, 123 insertions(+), 93 deletions(-) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index fa37f5d764..3cd1982f1d 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -11,21 +11,12 @@ Style/StringLiteralsInInterpolation: Layout/LineLength: Enabled: false -Style/RedundantReturn: - Enabled: false - -Style/IfUnlessModifier: - Enabled: false - Style/Documentation: Enabled: false Style/FrozenStringLiteralComment: Enabled: false -Layout/EmptyLineAfterGuardClause: - Enabled: false - Naming/ClassAndModuleCamelCase: Enabled: false diff --git a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs index 23d90d762d..90f4916d9c 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs @@ -26,7 +26,16 @@ public override void WriteCodeElement(CodeMethod codeElement, LanguageWriter wri var requestContentType = codeElement.Parameters.OfKind(CodeParameterKind.RequestBodyContentType); var requestParams = new RequestParams(requestBodyParam, config, requestContentType); WriteMethodPrototype(codeElement, writer); - AddNullChecks(codeElement, writer); + var wroteGuards = AddNullChecks(codeElement, writer); + var body = writer.CaptureLines(() => WriteMethodBody(codeElement, parentClass, requestParams, returnType, inherits, writer)); + if (wroteGuards && body.Count != 0) + writer.WriteLine(); + foreach (var line in body) + writer.WriteLine(line, false); + writer.CloseBlock("end"); + } + private void WriteMethodBody(CodeMethod codeElement, CodeClass parentClass, RequestParams requestParams, string returnType, bool inherits, LanguageWriter writer) + { switch (codeElement.Kind) { case CodeMethodKind.Serializer: @@ -74,16 +83,15 @@ public override void WriteCodeElement(CodeMethod codeElement, LanguageWriter wri case CodeMethodKind.ComposedTypeMarker: throw new InvalidOperationException("ComposedTypeMarker is not required as the wrapper is implemented directly."); default: - writer.WriteLine("return nil;"); + writer.WriteLine("nil"); break; } - writer.CloseBlock("end"); } private void WriteRawUrlBuilderBody(CodeClass parentClass, CodeMethod codeElement, LanguageWriter writer) { var rawUrlParameter = codeElement.Parameters.OfKind(CodeParameterKind.RawUrl) ?? throw new InvalidOperationException("RawUrlBuilder method should have a RawUrl parameter"); var requestAdapterProperty = parentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter) ?? throw new InvalidOperationException("RawUrlBuilder method should have a RequestAdapter property"); - writer.WriteLine($"return {parentClass.Name.ToFirstCharacterUpperCase()}.new({rawUrlParameter.Name.ToSnakeCase()}, @{requestAdapterProperty.Name.ToSnakeCase()})"); + writer.WriteLine($"{parentClass.Name.ToFirstCharacterUpperCase()}.new({rawUrlParameter.Name.ToSnakeCase()}, @{requestAdapterProperty.Name.ToSnakeCase()})"); } private const string DiscriminatorMappingVarName = "mapping_value"; private const string NodeVarName = "mapping_value_node"; @@ -116,11 +124,10 @@ private static void WriteFactoryMethodBodyForInheritedModel(CodeParameter parseN writer.CloseBlock("end", false); writer.CloseBlock("end"); } - writer.WriteLine($"return {parentClass.Name.ToFirstCharacterUpperCase()}.new"); + writer.WriteLine($"{parentClass.Name.ToFirstCharacterUpperCase()}.new"); } private void WriteFactoryMethodBodyForUnionModel(CodeParameter parseNodeParameter, CodeClass parentClass, LanguageWriter writer) { - writer.WriteLine($"result = {parentClass.Name.ToFirstCharacterUpperCase()}.new"); var parseNodeParameterName = parseNodeParameter.Name.ToSnakeCase(); var customProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .OrderBy(static x => x, new CodePropertyTypeComparer()) @@ -133,45 +140,60 @@ private void WriteFactoryMethodBodyForUnionModel(CodeParameter parseNodeParamete .Where(static x => !string.IsNullOrEmpty(x.mappedKey)) .ToArray(); var discriminatorPropertyName = parentClass.DiscriminatorInformation.DiscriminatorPropertyName; - if (complexPropertiesWithMappings.Length > 0 && !string.IsNullOrEmpty(discriminatorPropertyName)) + var nonComplexProperties = customProperties.Where(static x => x.Type is not CodeType propType || propType.TypeDefinition is not CodeClass || propType.CollectionKind != CodeTypeBase.CodeTypeCollectionKind.None).ToArray(); + var writesMappings = complexPropertiesWithMappings.Length > 0 && !string.IsNullOrEmpty(discriminatorPropertyName); + if (!writesMappings && nonComplexProperties.Length == 0) + { + writer.WriteLine($"{parentClass.Name.ToFirstCharacterUpperCase()}.new"); + return; + } + writer.WriteLine($"result = {parentClass.Name.ToFirstCharacterUpperCase()}.new"); + if (writesMappings) { writer.WriteLine($"{NodeVarName} = {parseNodeParameterName}.get_child_node(\"{RubyConventionService.SanitizeRubyDoubleQuoteLiteral(discriminatorPropertyName)}\")"); writer.StartBlock($"unless {NodeVarName}.nil?"); writer.WriteLine($"{DiscriminatorMappingVarName} = {NodeVarName}.get_string_value"); - var elseIfPrefix = string.Empty; - foreach (var (property, mappedKey) in complexPropertiesWithMappings) + // safe navigation: a ParseNode may yield a nil discriminator value, and the + // inherited factory's `case` path tolerates that, so this one must too + static string MappingCondition(string mappedKey) => $"{DiscriminatorMappingVarName}&.downcase == \"{RubyConventionService.SanitizeRubyDoubleQuoteLiteral(mappedKey)}\".downcase"; + if (complexPropertiesWithMappings.Length == 1) { - // safe navigation: a ParseNode may yield a nil discriminator value, and the - // inherited factory's `case` path tolerates that, so this one must too - writer.StartBlock($"{elseIfPrefix}if {DiscriminatorMappingVarName}&.downcase == \"{RubyConventionService.SanitizeRubyDoubleQuoteLiteral(mappedKey)}\".downcase"); - writer.WriteLine($"result.{property.Name.ToSnakeCase()} = {conventions.GetQualifiedTypeName(property.Type)}.new"); - writer.DecreaseIndent(); - elseIfPrefix = "els"; + var (property, mappedKey) = complexPropertiesWithMappings[0]; + writer.WriteLine($"result.{property.Name.ToSnakeCase()} = {conventions.GetQualifiedTypeName(property.Type)}.new if {MappingCondition(mappedKey)}"); + } + else + { + var elseIfPrefix = string.Empty; + foreach (var (property, mappedKey) in complexPropertiesWithMappings) + { + writer.StartBlock($"{elseIfPrefix}if {MappingCondition(mappedKey)}"); + writer.WriteLine($"result.{property.Name.ToSnakeCase()} = {conventions.GetQualifiedTypeName(property.Type)}.new"); + writer.DecreaseIndent(); + elseIfPrefix = "els"; + } + // the loop already restored the indent, so the chain's `end` must not decrease it again + writer.CloseBlock("end", false); } - // the loop already restored the indent, so the chain's `end` must not decrease it again - writer.CloseBlock("end", false); writer.CloseBlock("end"); } - foreach (var property in customProperties.Where(static x => x.Type is not CodeType propType || propType.TypeDefinition is not CodeClass || propType.CollectionKind != CodeTypeBase.CodeTypeCollectionKind.None)) + foreach (var property in nonComplexProperties) { var methodName = GetDeserializationMethodName(property.Type); writer.WriteLine($"val = {parseNodeParameterName}.{methodName}"); - writer.StartBlock("unless val.nil?"); - writer.WriteLine($"result.{property.Name.ToSnakeCase()} = val"); - writer.CloseBlock("end"); + writer.WriteLine($"result.{property.Name.ToSnakeCase()} = val unless val.nil?"); } - writer.WriteLine("return result"); + writer.WriteLine("result"); } private static string GetIntersectionValueVarName(CodeProperty property) => $"val_{property.Name.ToSnakeCase()}"; private void WriteComposedTypeGuardedSerialization(CodeProperty property, LanguageWriter writer) { var propertyName = property.Name.ToSnakeCase(); writer.WriteLine($"return if @{propertyName}.nil?"); + writer.WriteLine(); writer.WriteLine($"writer.{GetSerializationMethodName(property.Type)}(nil, @{propertyName})"); } private void WriteFactoryMethodBodyForIntersectionModel(CodeParameter parseNodeParameter, CodeClass parentClass, LanguageWriter writer) { - writer.WriteLine($"result = {parentClass.Name.ToFirstCharacterUpperCase()}.new"); var parseNodeParameterName = parseNodeParameter.Name.ToSnakeCase(); var customProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .OrderBy(static x => x, new CodePropertyTypeComparer(orderByDesc: true)) @@ -179,6 +201,12 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeParameter parseNodeP .ToArray(); var nonComplexProperties = customProperties.Where(static x => x.Type is not CodeType propType || propType.TypeDefinition is not CodeClass || propType.CollectionKind != CodeTypeBase.CodeTypeCollectionKind.None).ToArray(); var complexProperties = customProperties.Where(static x => x.Type is CodeType propType && propType.TypeDefinition is CodeClass && propType.CollectionKind == CodeTypeBase.CodeTypeCollectionKind.None).ToArray(); + if (customProperties.Length == 0) + { + writer.WriteLine($"{parentClass.Name.ToFirstCharacterUpperCase()}.new"); + return; + } + writer.WriteLine($"result = {parentClass.Name.ToFirstCharacterUpperCase()}.new"); // each property needs its own variable: a shared one would be reassigned inside the // previous branch of the if/elsif chain, so only the first property would ever be read foreach (var property in nonComplexProperties) @@ -192,9 +220,12 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeParameter parseNodeP var elseIfPrefix = string.Empty; foreach (var property in nonComplexProperties) { - writer.StartBlock(factoryBranchesChain - ? $"{elseIfPrefix}if !{GetIntersectionValueVarName(property)}.nil?" - : $"unless {GetIntersectionValueVarName(property)}.nil?"); + if (!factoryBranchesChain) + { + writer.WriteLine($"result.{property.Name.ToSnakeCase()} = {GetIntersectionValueVarName(property)} unless {GetIntersectionValueVarName(property)}.nil?"); + continue; + } + writer.StartBlock($"{elseIfPrefix}if !{GetIntersectionValueVarName(property)}.nil?"); writer.WriteLine($"result.{property.Name.ToSnakeCase()} = {GetIntersectionValueVarName(property)}"); writer.DecreaseIndent(); elseIfPrefix = "els"; @@ -215,18 +246,21 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeParameter parseNodeP writer.WriteLine($"result.{property.Name.ToSnakeCase()} = {conventions.GetQualifiedTypeName(property.Type)}.new"); } } - if (nonComplexProperties.Length > 0) + if (factoryBranchesChain && nonComplexProperties.Length > 0) writer.CloseBlock("end", false); - writer.WriteLine("return result"); + writer.WriteLine("result"); } - private static void AddNullChecks(CodeMethod codeElement, LanguageWriter writer) + private static bool AddNullChecks(CodeMethod codeElement, LanguageWriter writer) { - if (!codeElement.IsOverload) - foreach (var parameter in codeElement.Parameters - .Where(static x => !x.Optional && !x.IsOfKind(CodeParameterKind.PathParameters, CodeParameterKind.RequestAdapter)) - .Select(static x => x.Name.ToSnakeCase()) - .OrderBy(static x => x)) - writer.WriteLine($"raise StandardError, {RubyConventionService.ToRubyStringLiteral($"{parameter} cannot be null")} if {parameter}.nil?"); + if (codeElement.IsOverload) return false; + var parameters = codeElement.Parameters + .Where(static x => !x.Optional && !x.IsOfKind(CodeParameterKind.PathParameters, CodeParameterKind.RequestAdapter)) + .Select(static x => x.Name.ToSnakeCase()) + .OrderBy(static x => x) + .ToArray(); + foreach (var parameter in parameters) + writer.WriteLine($"raise StandardError, {RubyConventionService.ToRubyStringLiteral($"{parameter} cannot be null")} if {parameter}.nil?"); + return parameters.Length != 0; } private static void WriteQueryParametersMapper(CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer) { @@ -238,18 +272,18 @@ private static void WriteQueryParametersMapper(CodeMethod codeElement, CodeClass foreach (var escapedProperty in escapedProperties) { writer.StartBlock($"when {RubyConventionService.ToRubyStringLiteral(escapedProperty.Name)}"); - writer.WriteLine($"return \"{RubyConventionService.SanitizeRubyDoubleQuoteLiteral(escapedProperty.SerializationName)}\""); + writer.WriteLine($"\"{RubyConventionService.SanitizeRubyDoubleQuoteLiteral(escapedProperty.SerializationName)}\""); writer.DecreaseIndent(); } writer.StartBlock("else"); - writer.WriteLine($"return {parameterName}"); + writer.WriteLine(parameterName); writer.DecreaseIndent(); writer.CloseBlock("end", false); } private void WriteRequestBuilderBody(CodeClass parentClass, CodeMethod codeElement, LanguageWriter writer) { var importSymbol = conventions.GetQualifiedTypeName(codeElement.ReturnType); - conventions.AddRequestBuilderBody(parentClass, importSymbol, writer, prefix: "return ", pathParameters: codeElement.Parameters.Where(static x => x.IsOfKind(CodeParameterKind.Path))); + conventions.AddRequestBuilderBody(parentClass, importSymbol, writer, pathParameters: codeElement.Parameters.Where(static x => x.IsOfKind(CodeParameterKind.Path))); } private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod method, LanguageWriter writer) { @@ -260,9 +294,7 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me WriteSerializationRegistration(parentClass, method.DeserializerModules, writer, "register_default_deserializer"); if (!string.IsNullOrEmpty(method.BaseUrl)) { - writer.StartBlock($"if @{requestAdapterPropertyName}.get_base_url.nil? || @{requestAdapterPropertyName}.get_base_url.empty?"); - writer.WriteLine($"@{requestAdapterPropertyName}.set_base_url({RubyConventionService.ToRubyStringLiteral(method.BaseUrl)})"); - writer.CloseBlock("end"); + writer.WriteLine($"@{requestAdapterPropertyName}.set_base_url({RubyConventionService.ToRubyStringLiteral(method.BaseUrl)}) if @{requestAdapterPropertyName}.get_base_url.nil? || @{requestAdapterPropertyName}.get_base_url.empty?"); if (pathParametersProperty != null) writer.WriteLine($"@{pathParametersProperty.Name.ToSnakeCase()}[\"baseurl\"] = @{requestAdapterPropertyName}.get_base_url"); } @@ -370,7 +402,7 @@ private static void WriteGetterBody(CodeMethod codeElement, LanguageWriter write ArgumentNullException.ThrowIfNull(codeElement); ArgumentNullException.ThrowIfNull(writer); if (codeElement.AccessedProperty is not null) - writer.WriteLine($"return @{codeElement.AccessedProperty.NamePrefix}{codeElement.AccessedProperty.Name.ToSnakeCase()}"); + writer.WriteLine($"@{codeElement.AccessedProperty.NamePrefix}{codeElement.AccessedProperty.Name.ToSnakeCase()}"); } private void WriteIndexerBody(CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer) { @@ -378,7 +410,7 @@ private void WriteIndexerBody(CodeMethod codeElement, CodeClass parentClass, Lan codeElement.OriginalIndexer != null) writer.WriteLines($"{conventions.TempDictionaryVarName} = @{pathParametersProperty.NamePrefix}{pathParametersProperty.Name.ToSnakeCase()}.clone", $"{conventions.TempDictionaryVarName}[\"{RubyConventionService.SanitizeRubyDoubleQuoteLiteral(codeElement.OriginalIndexer.IndexParameter.SerializationName)}\"] = {codeElement.OriginalIndexer.IndexParameter.Name.ToSnakeCase()}"); - conventions.AddRequestBuilderBody(parentClass, conventions.GetQualifiedTypeName(codeElement.ReturnType), writer, conventions.TempDictionaryVarName, "return "); + conventions.AddRequestBuilderBody(parentClass, conventions.GetQualifiedTypeName(codeElement.ReturnType), writer, conventions.TempDictionaryVarName); } private void WriteDeserializerBody(CodeClass parentClass, LanguageWriter writer) { @@ -399,10 +431,10 @@ private void WriteDeserializerBodyForInheritedModel(CodeClass parentClass, Langu .ToArray(); if (entries.Length == 0) { - writer.WriteLine(inherits ? "return super" : "return {}"); + writer.WriteLine(inherits ? "super" : "{}"); return; } - writer.WriteLine(inherits ? "return super.merge(" : "return {"); + writer.WriteLine(inherits ? "super.merge(" : "{"); writer.IncreaseIndent(); for (var i = 0; i < entries.Length; i++) writer.WriteLine(i < entries.Length - 1 ? $"{entries[i]}," : entries[i]); @@ -416,12 +448,10 @@ private static void WriteDeserializerBodyForUnionModel(CodeClass parentClass, La .OrderBy(static x => x.Name, StringComparer.OrdinalIgnoreCase) .ToArray(); foreach (var property in complexProperties) - { - writer.StartBlock($"unless @{property.Name.ToSnakeCase()}.nil?"); - writer.WriteLine($"return @{property.Name.ToSnakeCase()}.get_field_deserializers"); - writer.CloseBlock("end"); - } - writer.WriteLine("return {}"); + writer.WriteLine($"return @{property.Name.ToSnakeCase()}.get_field_deserializers unless @{property.Name.ToSnakeCase()}.nil?"); + if (complexProperties.Length != 0) + writer.WriteLine(); + writer.WriteLine("{}"); } private static void WriteDeserializerBodyForIntersectionModel(CodeClass parentClass, LanguageWriter writer) { @@ -432,12 +462,11 @@ private static void WriteDeserializerBodyForIntersectionModel(CodeClass parentCl if (complexProperties.Length > 0) { var condition = string.Join(" || ", complexProperties.Select(x => $"@{x.Name.ToSnakeCase()}")); - writer.StartBlock($"if {condition}"); var propNames = string.Join(", ", complexProperties.Select(x => $"@{x.Name.ToSnakeCase()}")); - writer.WriteLine($"return MicrosoftKiotaAbstractions::ParseNodeHelper.merge_deserializers_for_intersection_wrapper({propNames})"); - writer.CloseBlock("end"); + writer.WriteLine($"return MicrosoftKiotaAbstractions::ParseNodeHelper.merge_deserializers_for_intersection_wrapper({propNames}) if {condition}"); + writer.WriteLine(); } - writer.WriteLine("return {}"); + writer.WriteLine("{}"); } private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requestParams, CodeClass parentClass, string returnType, LanguageWriter writer) { @@ -472,7 +501,7 @@ private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requ writer.WriteLine($"{errorMappingVarName}[\"{errorMapping.Key.ToUpperInvariant()}\"] = {getDeserializationLambda(errorMapping.Value)}"); } } - writer.WriteLine($"return @request_adapter.{genericTypeForSendMethod}(request_info, {returnType}, {errorMappingVarName})"); + writer.WriteLine($"@request_adapter.{genericTypeForSendMethod}(request_info, {returnType}, {errorMappingVarName})"); } private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams requestParams, CodeClass parentClass, LanguageWriter writer) @@ -487,15 +516,20 @@ private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams req var options = requestParams.Options; if (headers != null || queryString != null) { - writer.WriteLine($"unless {requestParams.requestConfiguration.Name.ToSnakeCase()}.nil?"); - writer.IncreaseIndent(); - if (headers != null) - writer.WriteLine($"request_info.add_headers_from_raw_object({requestParams.requestConfiguration.Name.ToSnakeCase()}.{headers.Name.ToSnakeCase()})"); - if (queryString != null) - writer.WriteLine($"request_info.set_query_string_parameters_from_raw_object({requestParams.requestConfiguration.Name.ToSnakeCase()}.{queryString.Name.ToSnakeCase()})"); - if (options != null) - writer.WriteLine($"request_info.add_request_options({requestParams.requestConfiguration.Name.ToSnakeCase()}.{options.Name.ToSnakeCase()})"); - writer.CloseBlock("end"); + var configurationName = requestParams.requestConfiguration.Name.ToSnakeCase(); + var statements = new[] { + headers is null ? null : $"request_info.add_headers_from_raw_object({configurationName}.{headers.Name.ToSnakeCase()})", + queryString is null ? null : $"request_info.set_query_string_parameters_from_raw_object({configurationName}.{queryString.Name.ToSnakeCase()})", + options is null ? null : $"request_info.add_request_options({configurationName}.{options.Name.ToSnakeCase()})", + }.OfType().ToArray(); + if (statements.Length == 1) + writer.WriteLine($"{statements[0]} unless {configurationName}.nil?"); + else + { + writer.StartBlock($"unless {configurationName}.nil?"); + writer.WriteLines(statements); + writer.CloseBlock("end"); + } } if (requestParams.requestBody != null) { @@ -521,7 +555,7 @@ private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams req writer.WriteLine($"request_info.http_method = :{codeElement.HttpMethod.Value.ToString().ToUpperInvariant()}"); if (codeElement.ShouldAddAcceptHeader) writer.WriteLine($"request_info.headers.try_add(\"Accept\", {RubyConventionService.ToRubyStringLiteral(codeElement.AcceptHeaderValue)})"); - writer.WriteLine("return request_info"); + writer.WriteLine("request_info"); } private static string GetPropertyCall(CodeProperty property, string defaultValue) => property == null ? defaultValue : $"@{property.NamePrefix}{property.Name.ToSnakeCase()}"; private void WriteSerializerBody(CodeClass parentClass, LanguageWriter writer) diff --git a/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs index 9111af5c36..68b4287f36 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodePropertyWriter.cs @@ -20,7 +20,7 @@ public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter w case CodePropertyKind.RequestBuilder: writer.WriteLine($"def {codeElement.Name.ToSnakeCase()}"); writer.IncreaseIndent(); - conventions.AddRequestBuilderBody(parentClass, conventions.GetQualifiedTypeName(codeElement.Type), writer, prefix: "return "); + conventions.AddRequestBuilderBody(parentClass, conventions.GetQualifiedTypeName(codeElement.Type), writer); writer.DecreaseIndent(); writer.WriteLine("end"); break; diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs index a441fef0c7..8eb8369a70 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeMethodWriterTests.cs @@ -226,7 +226,8 @@ public void WritesRequestBuilderInTheRootNamespaceWithoutALeadingSeparator() AddRequestProperties(); writer.Write(method); var result = tw.ToString(); - Assert.Contains("return RootRequestBuilder.new", result); + Assert.Contains("RootRequestBuilder.new", result); + Assert.DoesNotContain("return RootRequestBuilder.new", result); Assert.DoesNotContain("::RootRequestBuilder", result); } [Fact] @@ -416,7 +417,7 @@ public void WritesModelFactoryBody() Assert.Contains("case mapping_value", result); Assert.Contains("when \"ns.childmodel\"", result); Assert.Contains("return ChildModel.new", result); - Assert.Contains("return ParentModel.new", result); + Assert.Contains(result.Split('\n'), static x => x.Trim() == "ParentModel.new"); AssertExtensions.CurlyBracesAreClosed(result); } [Fact] @@ -571,7 +572,7 @@ public void DoesntWriteFactorySwitchOnEmptyPropertyName() Assert.DoesNotContain("mapping_value = mapping_value_node.get_string_value", result); Assert.DoesNotContain("case mapping_value", result); Assert.DoesNotContain("when \"ns.childmodel\"", result); - Assert.Contains("return ParentModel.new", result); + Assert.Contains(result.Split('\n'), static x => x.Trim() == "ParentModel.new"); AssertExtensions.CurlyBracesAreClosed(result); } [Fact] @@ -617,7 +618,7 @@ public void DoesntWriteFactorySwitchOnEmptyMappings() Assert.DoesNotContain("mapping_value = mapping_value_node.get_string_value", result); Assert.DoesNotContain("case mapping_value", result); Assert.DoesNotContain("when \"ns.childmodel\"", result); - Assert.Contains("return ParentModel.new", result); + Assert.Contains(result.Split('\n'), static x => x.Trim() == "ParentModel.new"); AssertExtensions.CurlyBracesAreClosed(result); } [Fact] @@ -641,7 +642,7 @@ public void WritesRequestGeneratorBody() Assert.Contains("add_headers_from_raw_object", result); Assert.Contains("add_request_options", result); Assert.Contains("set_content_from_parsable", result); - Assert.Contains("return request_info", result); + Assert.Contains(result.Split('\n'), static x => x.Trim() == "request_info"); } [Fact] public void WritesRequestGeneratorBodyWhenUrlTemplateIsOverrode() @@ -975,7 +976,8 @@ public void WritesIndexer() Assert.Contains("request_adapter", result); Assert.Contains("path_parameters", result); Assert.Contains("= id", result); - Assert.Contains("return Somecustomtype.new", result); + Assert.Contains("Somecustomtype.new", result); + Assert.DoesNotContain("return Somecustomtype.new", result); } [Fact] public void EscapesIndexerPathParameterName() @@ -1026,7 +1028,8 @@ public void WritesPathParameterRequestBuilder() Assert.Contains("path_parameters", result); Assert.Contains("path_param", result); Assert.DoesNotContain("pathParam", result); - Assert.Contains("return Somecustomtype.new", result); + Assert.Contains("Somecustomtype.new", result); + Assert.DoesNotContain("return Somecustomtype.new", result); } [Fact] public void WritesSetterToField() @@ -1231,7 +1234,8 @@ public void WritesWithUrl() AddRequestProperties(); writer.Write(method); var result = tw.ToString(); - Assert.Contains($"return {parentClass.Name.ToFirstCharacterUpperCase()}.new", result); + Assert.Contains($"{parentClass.Name.ToFirstCharacterUpperCase()}.new", result); + Assert.DoesNotContain("return ", result); } [Fact] public void WritesConstructorWithEnumValue() @@ -1465,7 +1469,8 @@ public void WritesNameMapperMethod() Assert.Contains("original_name", result); Assert.Contains("case", result); Assert.Contains("when \"select\"", result); - Assert.Contains("return \"%24select\"", result); + Assert.Contains("\"%24select\"", result); + Assert.DoesNotContain("return \"%24select\"", result); Assert.Contains("else", result); } [Fact] @@ -1532,7 +1537,7 @@ public void EscapesNameMapperMethodSerializationNames() writer.Write(method); var result = tw.ToString(); Assert.Contains("when \"filter\"", result); - Assert.Contains("return \"li\\\"ne\\#\\nbreak\"", result); + Assert.Contains("\"li\\\"ne\\#\\nbreak\"", result); } [Fact] public void DoesntWriteReadOnlyPropertiesInSerializerBody() @@ -1691,7 +1696,7 @@ public void WritesUnionFactoryBody() Assert.Contains("result = ParentClass.new", result); Assert.Contains("mapping_value_node", result); Assert.Contains("ComplexType1.new", result); - Assert.Contains("return result", result); + Assert.Contains(result.Split('\n'), static x => x.Trim() == "result"); Assert.DoesNotContain("ComplexType2.new", result); AssertBalancedBlocks(result); } @@ -1708,10 +1713,10 @@ public void WritesUnionFactoryBodySkipsEmptyMappings() method.AddParameter(new CodeParameter { Kind = CodeParameterKind.ParseNode, Name = "parseNode", Type = new CodeType { Name = "ParseNode" } }); writer.Write(method); var result = tw.ToString(); - Assert.Contains("result = ParentClass.new", result); + Assert.DoesNotContain("result =", result); Assert.DoesNotContain("mapping_value_node", result); Assert.DoesNotContain("unless", result); - Assert.Contains("return result", result); + Assert.Contains(result.Split('\n'), static x => x.Trim() == "ParentClass.new"); } [Fact] public void WritesUnionFactoryBodySkipsDiscriminatorWithoutAPropertyName() @@ -1731,7 +1736,7 @@ public void WritesUnionFactoryBodySkipsDiscriminatorWithoutAPropertyName() Assert.DoesNotContain("get_child_node(\"\")", result); Assert.DoesNotContain("mapping_value_node", result); Assert.Contains("result.string_value = val", result); - Assert.Contains("return result", result); + Assert.Contains(result.Split('\n'), static x => x.Trim() == "result"); AssertBalancedBlocks(result); } [Fact] @@ -1766,7 +1771,7 @@ public void WritesIntersectionFactoryBody() Assert.Contains("ComplexType1.new", result); Assert.Contains("ComplexType3.new", result); Assert.Contains("else", result); - Assert.Contains("return result", result); + Assert.Contains(result.Split('\n'), static x => x.Trim() == "result"); } [Fact] public void WritesIntersectionFactoryBodyOnlyComplex() @@ -1922,7 +1927,7 @@ public void WritesUnionDeserializerBody() Assert.Contains("@complex_type1_value.get_field_deserializers", result); Assert.DoesNotContain("get_field_deserializers()", result); Assert.DoesNotContain("complex_type2_value", result); - Assert.Contains("return {}", result); + Assert.Contains(result.Split('\n'), static x => x.Trim() == "{}"); AssertBalancedBlocks(result); } [Fact] @@ -1935,7 +1940,7 @@ public void WritesIntersectionDeserializerBody() Assert.DoesNotContain("super", result); Assert.Contains("merge_deserializers_for_intersection_wrapper(@complex_type1_value, @complex_type3_value)", result); Assert.DoesNotContain("complex_type2_value", result); - Assert.Contains("return {}", result); + Assert.Contains(result.Split('\n'), static x => x.Trim() == "{}"); AssertBalancedBlocks(result); } [Fact] From d322fdb056eb0f3f3c1e769cf4e653b3348e8560 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 12:56:33 +0100 Subject: [PATCH 14/25] style(ruby): start every generated file with the frozen string literal comment --- CHANGELOG.md | 1 + it/ruby/.rubocop.yml | 6 ------ .../Ruby/CodeClassDeclarationWriter.cs | 20 ++++++++++++------- .../Writers/Ruby/CodeEnumWriter.cs | 2 ++ .../Writers/Ruby/CodeNamespaceWriter.cs | 2 ++ .../Writers/Ruby/RubyConventionService.cs | 1 + .../Ruby/CodeClassDeclarationWriterTests.cs | 6 ++++++ .../Writers/Ruby/CodeEnumWriterTests.cs | 5 +++-- 8 files changed, 28 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 113fcf229f..b883183b47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Preserve models for multipart properties with default content types when other properties specify an encoding. [#7342](https://github.com/microsoft/kiota/issues/7342) - Dart: escape enum options named value or values to avoid conflicts with generated and built-in enum members. [#7807](https://github.com/microsoft/kiota/issues/7807) +- Ruby: generated files start with `# frozen_string_literal: true`, so string default values handed to user code are frozen. - Ruby: generated string literals are double quoted, so a base URL, URL template or content type containing a newline or tab now keeps it instead of a literal backslash sequence. - Ruby: namespaces with nothing to autoload no longer get an empty barrel file, and generated files no longer require them (561 fewer files in a GitHub client). - Ruby: a client generated with a multi-segment `--namespace-name`, such as `integration_test.client`, failed to load because its root file was written one directory too deep. diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index 3cd1982f1d..29a75fa493 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -14,18 +14,12 @@ Layout/LineLength: Style/Documentation: Enabled: false -Style/FrozenStringLiteralComment: - Enabled: false - Naming/ClassAndModuleCamelCase: Enabled: false Naming/AccessorMethodName: Enabled: false -Lint/EmptyFile: - Enabled: false - Metrics/MethodLength: Enabled: false diff --git a/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs index 19b6220a3e..05249e350a 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeClassDeclarationWriter.cs @@ -27,16 +27,15 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit var currentNamespace = codeElement.GetImmediateParentOfType(); if (codeElement.Parent?.Parent is not CodeClass) { - foreach (var codeUsing in codeElement.Usings + var requires = codeElement.Usings .Where(static x => x.IsExternal) .Select(static x => x.Declaration?.Name?.ToSnakeCase()) .Where(static x => !string.IsNullOrEmpty(x)) .GroupBy(static x => x) .Select(static x => x.Key) - .Order(StringComparer.OrdinalIgnoreCase)) - writer.WriteLine($"require {RubyConventionService.ToRubyStringLiteral(codeUsing)}"); - - foreach (var relativePath in codeElement.Usings + .Order(StringComparer.OrdinalIgnoreCase) + .Select(static x => $"require {RubyConventionService.ToRubyStringLiteral(x)}") + .Concat(codeElement.Usings .Where(static x => !x.IsExternal) .DistinctBy(static x => $"{x.Name}{x.Declaration?.Name}", StringComparer.OrdinalIgnoreCase) .Select(x => x.Declaration?.Name?.StartsWith('.') ?? false ? @@ -44,8 +43,15 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit relativeImportManager.GetRelativeImportPathForUsing(x, currentNamespace)) .Select(static x => x.Item3) .Distinct() - .Order(StringComparer.OrdinalIgnoreCase)) - writer.WriteLine($"require_relative {RubyConventionService.ToRubyStringLiteral(relativePath.ToSnakeCase())}"); + .Order(StringComparer.OrdinalIgnoreCase) + .Select(static x => $"require_relative {RubyConventionService.ToRubyStringLiteral(x.ToSnakeCase())}")) + .ToArray(); + writer.WriteLine(RubyConventionService.FrozenStringLiteralComment); + if (requires.Length != 0) + { + writer.WriteLine(); + writer.WriteLines(requires); + } } if (codeElement.Parent?.Parent is CodeClass) RubyConventionService.WriteMemberSeparator(writer); diff --git a/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs index 982511c936..59ca4a8245 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeEnumWriter.cs @@ -13,8 +13,10 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write { ArgumentNullException.ThrowIfNull(codeElement); ArgumentNullException.ThrowIfNull(writer); + writer.WriteLine(RubyConventionService.FrozenStringLiteralComment); if (!codeElement.Options.Any()) return; + writer.WriteLine(); if (codeElement.Parent is CodeNamespace ns) conventions.WriteNamespaceModules(ns, writer); conventions.WriteShortDescription(codeElement, writer); diff --git a/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs index 8f555a3cbd..846545fa8e 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs @@ -28,6 +28,8 @@ public override void WriteCodeElement(CodeNamespace codeElement, LanguageWriter if (RubyConventionService.IsAutoloaded(x)) autoloaded.Add(x); }); if (autoloaded.Count == 0) return; + writer.WriteLine(RubyConventionService.FrozenStringLiteralComment); + writer.WriteLine(); conventions.WriteNamespaceModules(codeElement, writer); foreach (var element in autoloaded) writer.WriteLine($"autoload :{element.Name.ToFirstCharacterUpperCase()}, ::File.expand_path({RubyConventionService.ToRubyStringLiteral(PathSegmenter.GetRelativeFileName(codeElement, element).ToSnakeCase())}, __dir__)"); diff --git a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs index 8c689e7314..89c4be6f71 100644 --- a/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs +++ b/src/Kiota.Builder/Writers/Ruby/RubyConventionService.cs @@ -22,6 +22,7 @@ public class RubyConventionService : CommonLanguageConventionService CodeEnum codeEnum => codeEnum.Parent is CodeNamespace ns && !ns.HasClassNamedAfterItself() && codeEnum.Options.Any(), _ => false, }; + internal const string FrozenStringLiteralComment = "# frozen_string_literal: true"; // one blank line between class members, none at the start of a block internal static void WriteMemberSeparator(LanguageWriter writer) { diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeClassDeclarationWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeClassDeclarationWriterTests.cs index 60029f8a4e..c7d420f152 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeClassDeclarationWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeClassDeclarationWriterTests.cs @@ -80,6 +80,12 @@ public void WritesOneIncludePerMixinKeepingMethodLookupOrder() Assert.True(result.IndexOf("include Second", StringComparison.Ordinal) < result.IndexOf("include First", StringComparison.Ordinal)); } [Fact] + public void StartsATopLevelClassFileWithTheFrozenStringLiteralComment() + { + codeElementWriter.WriteCodeElement(parentClass.StartBlock, writer); + Assert.StartsWith("# frozen_string_literal: true", tw.ToString(), StringComparison.Ordinal); + } + [Fact] public void WritesInheritance() { var declaration = parentClass.StartBlock; diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs index 8213721947..957f03ef8f 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeEnumWriterTests.cs @@ -51,11 +51,12 @@ public void WritesEnum() AssertExtensions.CurlyBracesAreClosed(result); } [Fact] - public void DoesntWriteAnythingOnNoOption() + public void WritesOnlyTheMagicCommentOnNoOption() { writer.Write(currentEnum); var result = tw.ToString(); - Assert.Empty(result); + // the file still has to exist and not be empty, but defines nothing + Assert.Equal("# frozen_string_literal: true", result.Trim()); } [Fact] public void WritesModule() From 733be574782604f035cce801436391670f1361eb Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 13:06:12 +0100 Subject: [PATCH 15/25] style(ruby): let a subclass inherit initialize and the deserializer when it adds nothing --- it/ruby/.rubocop.yml | 4 ---- src/Kiota.Builder/Refiners/RubyRefiner.cs | 15 ++++++++++++++- .../Refiners/RubyLanguageRefinerTests.cs | 14 ++++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index 29a75fa493..321ad07ac5 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -55,10 +55,6 @@ Metrics/CyclomaticComplexity: Metrics/PerceivedComplexity: Enabled: false -# Generated factory methods may just delegate to super -Lint/UselessMethodDefinition: - Enabled: false - # one accessor per property, each with its own doc comment Style/AccessorGrouping: EnforcedStyle: separated diff --git a/src/Kiota.Builder/Refiners/RubyRefiner.cs b/src/Kiota.Builder/Refiners/RubyRefiner.cs index 8946a03be6..71ef6b6e43 100644 --- a/src/Kiota.Builder/Refiners/RubyRefiner.cs +++ b/src/Kiota.Builder/Refiners/RubyRefiner.cs @@ -81,11 +81,13 @@ public override Task RefineAsync(CodeNamespace generatedCode, CancellationToken true ); ReplaceReservedNames(generatedCode, reservedNamesProvider, x => $"{x}_escaped"); + // Ruby inherits initialize, so a subclass needs one only for defaults of its own AddConstructorsForDefaultValues( generatedCode, - true, + false, false, [CodeClassKind.RequestConfiguration]); + RemoveDeserializersThatOnlyCallSuper(generatedCode); ShortenLongNamespaceNames(generatedCode); if (generatedCode.FindNamespaceByName(_configuration.ClientNamespaceName)?.Parent is CodeNamespace parentOfClientNS) AddNamespaceModuleImports(parentOfClientNS, generatedCode); @@ -250,6 +252,17 @@ private static void CorrectPropertyType(CodeProperty currentProperty) new (static x => x is CodeProperty prop && prop.IsOfKind(CodePropertyKind.BackingStore), "microsoft_kiota_abstractions", "BackingStore", "BackedModel", "BackingStoreFactorySingleton" ), }; + // a subclass with no fields of its own inherits the deserializer map unchanged + private static void RemoveDeserializersThatOnlyCallSuper(CodeElement currentElement) + { + if (currentElement is CodeClass currentClass && + currentClass.IsOfKind(CodeClassKind.Model) && + currentClass.StartBlock.Inherits is not null && + currentClass.OriginalComposedType is null && + !currentClass.Properties.Any(static x => x.IsOfKind(CodePropertyKind.Custom) && !x.ExistsInBaseType)) + currentClass.RemoveMethodByKinds(CodeMethodKind.Deserializer); + CrawlTree(currentElement, RemoveDeserializersThatOnlyCallSuper); + } private static void AddNamespaceModuleImports(CodeNamespace clientNamespaceParent, CodeElement current) { if (current is CodeClass currentClass) diff --git a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs index d2aee3c3e3..28f8b5d070 100644 --- a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs +++ b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs @@ -151,6 +151,20 @@ public async Task DoesNotAddAccessorMethodsForModelPropertiesAsync() Assert.Contains(model.Properties, static x => x.IsOfKind(CodePropertyKind.Custom)); } [Fact] + public async Task LetsASubclassWithNothingOfItsOwnInheritInitializeAndTheDeserializerAsync() + { + var baseModel = graphNS.AddClass(new CodeClass { Name = "animal", Kind = CodeClassKind.Model }).First(); + baseModel.AddProperty(new CodeProperty { Name = "additionalData", Kind = CodePropertyKind.AdditionalData, Type = new CodeType { Name = "IDictionary" }, DefaultValue = "{}" }); + baseModel.AddMethod(new CodeMethod { Name = "getFieldDeserializers", Kind = CodeMethodKind.Deserializer, ReturnType = new CodeType { Name = "IDictionary>" } }); + var derivedModel = graphNS.AddClass(new CodeClass { Name = "cat", Kind = CodeClassKind.Model }).First(); + derivedModel.StartBlock.Inherits = new CodeType { Name = "animal", TypeDefinition = baseModel }; + derivedModel.AddMethod(new CodeMethod { Name = "getFieldDeserializers", Kind = CodeMethodKind.Deserializer, ReturnType = new CodeType { Name = "IDictionary>" } }); + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.Contains(baseModel.Methods, static x => x.IsOfKind(CodeMethodKind.Constructor)); + Assert.Contains(baseModel.Methods, static x => x.IsOfKind(CodeMethodKind.Deserializer)); + Assert.DoesNotContain(derivedModel.Methods, static x => x.IsOfKind(CodeMethodKind.Constructor, CodeMethodKind.Deserializer)); + } + [Fact] public async Task DoesNotKeepCancellationParametersInRequestExecutorsAsync() { var model = root.AddClass(new CodeClass From d14179240dc9af768807d82eb4022e80ec235853 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 13:12:11 +0100 Subject: [PATCH 16/25] feat(ruby): generate eager_load! on the client root module --- CHANGELOG.md | 1 + it/ruby/spec/integration_test_spec.rb | 13 ++-------- .../CodeRenderers/RubyCodeRenderer.cs | 6 +++-- src/Kiota.Builder/Refiners/RubyRefiner.cs | 13 ++++++---- .../Writers/Ruby/CodeNamespaceWriter.cs | 25 +++++++++++++++++-- src/Kiota.Builder/Writers/Ruby/RubyWriter.cs | 2 +- .../CodeRenderers/RubyCodeRendererTests.cs | 7 ++++++ .../Refiners/RubyLanguageRefinerTests.cs | 11 ++++++++ .../Writers/Ruby/CodeNamespaceWriterTests.cs | 11 ++++++++ 9 files changed, 68 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b883183b47..b8be73a808 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Preserve models for multipart properties with default content types when other properties specify an encoding. [#7342](https://github.com/microsoft/kiota/issues/7342) - Dart: escape enum options named value or values to avoid conflicts with generated and built-in enum members. [#7807](https://github.com/microsoft/kiota/issues/7807) +- Ruby: the client's root module has an `eager_load!` method that loads every autoloaded model, for servers that preload before forking. - Ruby: generated files start with `# frozen_string_literal: true`, so string default values handed to user code are frozen. - Ruby: generated string literals are double quoted, so a base URL, URL template or content type containing a newline or tab now keeps it instead of a literal backslash sequence. - Ruby: namespaces with nothing to autoload no longer get an empty barrel file, and generated files no longer require them (561 fewer files in a GitHub client). diff --git a/it/ruby/spec/integration_test_spec.rb b/it/ruby/spec/integration_test_spec.rb index 18668d30ba..4c94d100e6 100644 --- a/it/ruby/spec/integration_test_spec.rb +++ b/it/ruby/spec/integration_test_spec.rb @@ -13,16 +13,7 @@ end # models are autoloaded, so a bad registration only fails when the constant is first used - it "resolves every constant the client registers" do - visit = lambda do |mod, seen| - next if seen.key?(mod) - - seen[mod] = true - mod.constants(false).each do |name| - value = mod.const_get(name, false) - visit.call(value, seen) if value.instance_of?(Module) - end - end - expect { visit.call(Integration_test::Client, {}) }.not_to raise_error + it "eager loads every constant the client registers" do + expect { Integration_test::Client.eager_load! }.not_to raise_error end end diff --git a/src/Kiota.Builder/CodeRenderers/RubyCodeRenderer.cs b/src/Kiota.Builder/CodeRenderers/RubyCodeRenderer.cs index 7261823053..1c7cb5b596 100644 --- a/src/Kiota.Builder/CodeRenderers/RubyCodeRenderer.cs +++ b/src/Kiota.Builder/CodeRenderers/RubyCodeRenderer.cs @@ -1,4 +1,5 @@ -using Kiota.Builder.CodeDOM; +using System; +using Kiota.Builder.CodeDOM; using Kiota.Builder.Configuration; using Kiota.Builder.Writers.Ruby; @@ -8,5 +9,6 @@ public class RubyCodeRenderer : CodeRenderer { public RubyCodeRenderer(GenerationConfiguration configuration) : base(configuration) { } public override bool ShouldRenderNamespaceFile(CodeNamespace codeNamespace) => - codeNamespace is not null && base.ShouldRenderNamespaceFile(codeNamespace) && RubyConventionService.HasAutoloadedMembers(codeNamespace); + codeNamespace is not null && base.ShouldRenderNamespaceFile(codeNamespace) && + (RubyConventionService.HasAutoloadedMembers(codeNamespace) || codeNamespace.Name.Equals(Configuration.ClientNamespaceName, StringComparison.OrdinalIgnoreCase)); } diff --git a/src/Kiota.Builder/Refiners/RubyRefiner.cs b/src/Kiota.Builder/Refiners/RubyRefiner.cs index 71ef6b6e43..60837f26a8 100644 --- a/src/Kiota.Builder/Refiners/RubyRefiner.cs +++ b/src/Kiota.Builder/Refiners/RubyRefiner.cs @@ -116,7 +116,7 @@ public override Task RefineAsync(CodeNamespace generatedCode, CancellationToken "ParseNode", addUsings: true ); - RequireBarrelsOfAutoloadedTypes(generatedCode); + RequireBarrelsOfAutoloadedTypes(generatedCode, _configuration.ClientNamespaceName); }, cancellationToken); } private static void ShortenLongNamespaceNames(CodeElement currentElement) @@ -296,13 +296,16 @@ private static void AddModules(CodeNamespace clientNamespaceParent, CodeNamespac } }; // an autoloaded file is only ever loaded through its barrel, so other files require the barrel - private static void RequireBarrelsOfAutoloadedTypes(CodeElement currentElement) + private static void RequireBarrelsOfAutoloadedTypes(CodeElement currentElement, string clientNamespaceName) { if (currentElement is CodeClass { Parent: CodeNamespace currentNamespace } currentClass) { - // a namespace with nothing to autoload gets no barrel file, so nothing may require one + // a namespace with nothing to autoload gets no barrel file, so nothing may require one; + // the client's root file always exists and only the client requires it, for eager_load! + var isClient = currentClass.Methods.Any(static x => x.IsOfKind(CodeMethodKind.ClientConstructor)); currentClass.StartBlock.RemoveUsings(currentClass.Usings - .Where(static x => !x.IsExternal && x.Declaration?.TypeDefinition is CodeNamespace ns && !RubyConventionService.HasAutoloadedMembers(ns)) + .Where(x => !x.IsExternal && x.Declaration?.TypeDefinition is CodeNamespace ns && !RubyConventionService.HasAutoloadedMembers(ns) && + !(isClient && ns.Name.Equals(clientNamespaceName, StringComparison.OrdinalIgnoreCase))) .ToArray()); var typeUsings = currentClass.Usings .Where(static x => !x.IsExternal && x.Declaration?.TypeDefinition is CodeElement definition && RubyConventionService.IsAutoloaded(definition)) @@ -320,7 +323,7 @@ private static void RequireBarrelsOfAutoloadedTypes(CodeElement currentElement) currentClass.AddUsing(barrels); } } - CrawlTree(currentElement, RequireBarrelsOfAutoloadedTypes); + CrawlTree(currentElement, x => RequireBarrelsOfAutoloadedTypes(x, clientNamespaceName)); } private static void CorrectImplements(ProprietableBlockDeclaration block) { diff --git a/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs index 846545fa8e..b7fbd164ef 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs @@ -10,10 +10,12 @@ namespace Kiota.Builder.Writers.Ruby; public class CodeNamespaceWriter : BaseElementWriter { private readonly RubyPathSegmenter PathSegmenter; - public CodeNamespaceWriter(RubyConventionService conventionService, RubyPathSegmenter pathSegmenter) : base(conventionService) + private readonly string? ClientNamespaceName; + public CodeNamespaceWriter(RubyConventionService conventionService, RubyPathSegmenter pathSegmenter, string? clientNamespaceName = null) : base(conventionService) { ArgumentNullException.ThrowIfNull(pathSegmenter); PathSegmenter = pathSegmenter; + ClientNamespaceName = clientNamespaceName; } public override void WriteCodeElement(CodeNamespace codeElement, LanguageWriter writer) { @@ -27,12 +29,31 @@ public override void WriteCodeElement(CodeNamespace codeElement, LanguageWriter { if (RubyConventionService.IsAutoloaded(x)) autoloaded.Add(x); }); - if (autoloaded.Count == 0) return; + var isClientNamespace = codeElement.Name.Equals(ClientNamespaceName, StringComparison.OrdinalIgnoreCase); + if (autoloaded.Count == 0 && !isClientNamespace) return; writer.WriteLine(RubyConventionService.FrozenStringLiteralComment); writer.WriteLine(); conventions.WriteNamespaceModules(codeElement, writer); foreach (var element in autoloaded) writer.WriteLine($"autoload :{element.Name.ToFirstCharacterUpperCase()}, ::File.expand_path({RubyConventionService.ToRubyStringLiteral(PathSegmenter.GetRelativeFileName(codeElement, element).ToSnakeCase())}, __dir__)"); + if (isClientNamespace) + WriteEagerLoad(writer); conventions.WriteNamespaceClosing(codeElement, writer); } + private static void WriteEagerLoad(LanguageWriter writer) + { + RubyConventionService.WriteMemberSeparator(writer); + writer.WriteLine("# Loads every model and enum registered for autoload, for example before a server forks."); + writer.StartBlock("def self.eager_load!"); + writer.WriteLines("pending = [self]", "seen = {}"); + writer.StartBlock("until pending.empty?"); + writer.WriteLines("mod = pending.pop", "next if seen.key?(mod)"); + writer.WriteLine(); + writer.WriteLine("seen[mod] = true"); + writer.StartBlock("mod.constants(false).each do |name|"); + writer.WriteLines("value = mod.const_get(name, false)", "pending << value if value.instance_of?(::Module)"); + writer.CloseBlock("end"); + writer.CloseBlock("end"); + writer.CloseBlock("end"); + } } diff --git a/src/Kiota.Builder/Writers/Ruby/RubyWriter.cs b/src/Kiota.Builder/Writers/Ruby/RubyWriter.cs index 9561fe308b..abb90ebfb1 100644 --- a/src/Kiota.Builder/Writers/Ruby/RubyWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/RubyWriter.cs @@ -11,7 +11,7 @@ public RubyWriter(string rootPath, string clientNamespaceName) : base(" ", 2) var pathSegmenter = new RubyPathSegmenter(rootPath, clientNamespaceName); AddOrReplaceCodeElementWriter(new CodeClassDeclarationWriter(conventionService, clientNamespaceName, pathSegmenter)); AddOrReplaceCodeElementWriter(new CodeBlockEndWriter(conventionService)); - AddOrReplaceCodeElementWriter(new CodeNamespaceWriter(conventionService, pathSegmenter)); + AddOrReplaceCodeElementWriter(new CodeNamespaceWriter(conventionService, pathSegmenter, clientNamespaceName)); AddOrReplaceCodeElementWriter(new CodeEnumWriter(conventionService)); AddOrReplaceCodeElementWriter(new CodeMethodWriter(conventionService)); AddOrReplaceCodeElementWriter(new CodePropertyWriter(conventionService)); diff --git a/tests/Kiota.Builder.Tests/CodeRenderers/RubyCodeRendererTests.cs b/tests/Kiota.Builder.Tests/CodeRenderers/RubyCodeRendererTests.cs index 92f94b890f..3e153497fa 100644 --- a/tests/Kiota.Builder.Tests/CodeRenderers/RubyCodeRendererTests.cs +++ b/tests/Kiota.Builder.Tests/CodeRenderers/RubyCodeRendererTests.cs @@ -17,6 +17,13 @@ public class RubyCodeRendererTests public void IsTheRendererForRuby() => Assert.IsType(CodeRenderer.GetCodeRender(new GenerationConfiguration { Language = GenerationLanguage.Ruby })); + [Fact] + public void AlwaysWritesTheClientNamespaceFile() + { + var ns = root.AddNamespace("graph"); + ns.AddClass(new CodeClass { Name = "graphServiceClient", Kind = CodeClassKind.RequestBuilder }); + Assert.True(renderer.ShouldRenderNamespaceFile(ns)); + } [Fact] public void SkipsTheBarrelOfANamespaceWithOnlyRequestBuilders() { diff --git a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs index 28f8b5d070..9d3aa84273 100644 --- a/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs +++ b/tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs @@ -165,6 +165,17 @@ public async Task LetsASubclassWithNothingOfItsOwnInheritInitializeAndTheDeseria Assert.DoesNotContain(derivedModel.Methods, static x => x.IsOfKind(CodeMethodKind.Constructor, CodeMethodKind.Deserializer)); } [Fact] + public async Task RequiresTheClientRootFileOnlyFromTheClientAsync() + { + var client = graphNS.AddClass(new CodeClass { Name = "graphClient", Kind = CodeClassKind.RequestBuilder }).First(); + client.AddMethod(new CodeMethod { Name = "constructor", Kind = CodeMethodKind.ClientConstructor, ReturnType = new CodeType { Name = "void" } }); + var usersNS = graphNS.AddNamespace($"{graphNS.Name}.users"); + var usersBuilder = usersNS.AddClass(new CodeClass { Name = "usersRequestBuilder", Kind = CodeClassKind.RequestBuilder }).First(); + await ILanguageRefiner.RefineAsync(new GenerationConfiguration { Language = GenerationLanguage.Ruby, ClientNamespaceName = graphNS.Name }, root, cancellationToken: TestContext.Current.CancellationToken); + Assert.Contains(client.Usings, x => x.Declaration?.TypeDefinition == graphNS); + Assert.DoesNotContain(usersBuilder.Usings, x => x.Declaration?.TypeDefinition == graphNS); + } + [Fact] public async Task DoesNotKeepCancellationParametersInRequestExecutorsAsync() { var model = root.AddClass(new CodeClass diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs index d70cd4bacc..83f30104ba 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs @@ -51,6 +51,17 @@ public void RegistersModelsAndEnumsForAutoloadInsteadOfRequiringThem() Assert.Contains("autoload :Color, ::File.expand_path(\"color\", __dir__)", result, StringComparison.Ordinal); } [Fact] + public void WritesEagerLoadInTheClientNamespaceEvenWithNothingToAutoload() + { + var clientWriter = new CodeNamespaceWriter(new RubyConventionService(), new RubyPathSegmenter(Path.GetTempPath(), ClientNamespaceName), ClientNamespaceName); + var clientNamespace = modelsNamespace.Parent as CodeNamespace ?? throw new InvalidOperationException("models namespace has no parent"); + clientWriter.WriteCodeElement(clientNamespace.FindNamespaceByName(ClientNamespaceName) ?? clientNamespace.AddNamespace(ClientNamespaceName), writer); + var result = tw.ToString(); + Assert.Contains("def self.eager_load!", result, StringComparison.Ordinal); + Assert.Contains("instance_of?(::Module)", result, StringComparison.Ordinal); + Assert.Contains("module Graph", result, StringComparison.Ordinal); + } + [Fact] public void DoesNotRegisterAnEnumWithoutOptions() { // the enum writer emits nothing for it, so the constant would never be defined From e6fe299650e7716b401712d968a3fdbf0880b47f Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 13:16:40 +0100 Subject: [PATCH 17/25] docs(ruby): give every cop the generated code still skips a reason --- it/ruby/.rubocop.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/it/ruby/.rubocop.yml b/it/ruby/.rubocop.yml index 321ad07ac5..b3a40f9eaf 100644 --- a/it/ruby/.rubocop.yml +++ b/it/ruby/.rubocop.yml @@ -8,33 +8,43 @@ Style/StringLiteralsInInterpolation: Enabled: true EnforcedStyle: double_quotes +# generated lines embed URL templates, qualified constants and API descriptions Layout/LineLength: Enabled: false +# class docs come from optional API descriptions; filler comments would be noise Style/Documentation: Enabled: false +# module and class names come from the namespace name and API names; renaming them is breaking Naming/ClassAndModuleCamelCase: Enabled: false +# the runtime calls get_field_deserializers and get_query_parameter by name Naming/AccessorMethodName: Enabled: false +# generated method size tracks the API surface, one line per property, mapping or error code Metrics/MethodLength: Enabled: false +# generated method size tracks the API surface, one line per property, mapping or error code Metrics/AbcSize: Enabled: false +# enums are CamelCase hash constants that users reference; renaming them is breaking Naming/ConstantName: Enabled: false +# is_ and has_ names mirror the API's property names, as in every other Kiota language Naming/PredicatePrefix: Enabled: false +# generated class size tracks the API surface Metrics/ClassLength: Enabled: false +# generated module size tracks the API surface Metrics/ModuleLength: Enabled: false From dd78a37bc0394b258a277ad0402a2c4b42597d6d Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 14:02:20 +0100 Subject: [PATCH 18/25] test: cover a three-level hierarchy entered through its base class --- .github/workflows/idempotency-tests.yml | 1 + .github/workflows/integration-tests.yml | 1 + it/config.json | 3 ++ .../integration_test_inheritance.rb | 28 ++++++++++ .../InheritingThreeLevels.yaml | 51 +++++++++++++++++++ 5 files changed, 84 insertions(+) create mode 100644 it/ruby/spec/inheritance/integration_test_inheritance.rb create mode 100644 tests/Kiota.Builder.IntegrationTests/InheritingThreeLevels.yaml diff --git a/.github/workflows/idempotency-tests.yml b/.github/workflows/idempotency-tests.yml index 1c797c5d1e..2b34cb1743 100644 --- a/.github/workflows/idempotency-tests.yml +++ b/.github/workflows/idempotency-tests.yml @@ -87,6 +87,7 @@ jobs: - dart description: - "./tests/Kiota.Builder.IntegrationTests/InheritingErrors.yaml" + - "./tests/Kiota.Builder.IntegrationTests/InheritingThreeLevels.yaml" - "./tests/Kiota.Builder.IntegrationTests/NoUnderscoresInModel.yaml" - "oas::petstore" - "https://api.twitter.com/2/openapi.json" diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index 5e5cb2deae..73ee98241f 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -88,6 +88,7 @@ jobs: - dart description: - "./tests/Kiota.Builder.IntegrationTests/InheritingErrors.yaml" + - "./tests/Kiota.Builder.IntegrationTests/InheritingThreeLevels.yaml" - "./tests/Kiota.Builder.IntegrationTests/EnumHandling.yaml" - "./tests/Kiota.Builder.IntegrationTests/NoUnderscoresInModel.yaml" - "./tests/Kiota.Builder.IntegrationTests/ToDoApi.yaml" diff --git a/it/config.json b/it/config.json index 8e35cb9de5..af76a736d8 100644 --- a/it/config.json +++ b/it/config.json @@ -2,6 +2,9 @@ "./tests/Kiota.Builder.IntegrationTests/InheritingErrors.yaml": { "MockServerITFolder": "basic" }, + "./tests/Kiota.Builder.IntegrationTests/InheritingThreeLevels.yaml": { + "MockServerITFolder": "inheritance" + }, "./tests/Kiota.Builder.IntegrationTests/GeneratesUritemplateHints.yaml": { "MockServerITFolder": "query-params" }, diff --git a/it/ruby/spec/inheritance/integration_test_inheritance.rb b/it/ruby/spec/inheritance/integration_test_inheritance.rb new file mode 100644 index 0000000000..dce1c9cba2 --- /dev/null +++ b/it/ruby/spec/inheritance/integration_test_inheritance.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +RSpec.describe Integration_test do + let(:client) do + request_adapter = MicrosoftKiotaFaraday::FaradayRequestAdapter.new(MicrosoftKiotaAbstractions::AnonymousAuthenticationProvider.new) + request_adapter.set_base_url("http://127.0.0.1:1080") + Integration_test::Client::ApiClient.new(request_adapter) + end + + it "deserializes a response typed as the base class into the most derived class" do + animal = client.api.v1.animals.get.resume + + expect(animal).to be_a(Integration_test::Client::Models::Kitten) + expect([animal.kind, animal.name, animal.lives, animal.age]).to eq(["kitten", "Tom", 9, 1]) + end + + it "serializes the properties of every level" do + kitten = Integration_test::Client::Models::Kitten.new + kitten.kind = "kitten" + kitten.name = "Tom" + kitten.lives = 9 + kitten.age = 1 + writer = MicrosoftKiotaSerializationJson::JsonSerializationWriter.new + writer.write_object_value(nil, kitten) + + expect(JSON.parse(writer.get_serialized_content)).to eq("kind" => "kitten", "name" => "Tom", "lives" => 9, "age" => 1) + end +end diff --git a/tests/Kiota.Builder.IntegrationTests/InheritingThreeLevels.yaml b/tests/Kiota.Builder.IntegrationTests/InheritingThreeLevels.yaml new file mode 100644 index 0000000000..0618703426 --- /dev/null +++ b/tests/Kiota.Builder.IntegrationTests/InheritingThreeLevels.yaml @@ -0,0 +1,51 @@ +openapi: 3.0.3 +info: + title: Animal Shelter API + version: 1.0.0 +paths: + /api/v1/animals: + get: + summary: Retrieves an animal + operationId: getAnimal + responses: + "200": + description: Example. + content: + application/json: + schema: + $ref: "#/components/schemas/Animal" + example: + kind: kitten + name: Tom + lives: 9 + age: 1 +components: + schemas: + Animal: + type: object + required: + - kind + discriminator: + propertyName: kind + mapping: + cat: "#/components/schemas/Cat" + kitten: "#/components/schemas/Kitten" + properties: + kind: + type: string + name: + type: string + Cat: + allOf: + - $ref: "#/components/schemas/Animal" + - type: object + properties: + lives: + type: integer + Kitten: + allOf: + - $ref: "#/components/schemas/Cat" + - type: object + properties: + age: + type: integer From 75e7485db34fba13be717d9235feb34db222f3bf Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 14:02:20 +0100 Subject: [PATCH 19/25] test(ruby): port the discriminator and query parameter integration tests --- .../integration_test_discriminator.rb | 48 +++++++++++++++++++ .../integration_test_query_params.rb | 25 ++++++++++ 2 files changed, 73 insertions(+) create mode 100644 it/ruby/spec/discriminator/integration_test_discriminator.rb create mode 100644 it/ruby/spec/query-params/integration_test_query_params.rb diff --git a/it/ruby/spec/discriminator/integration_test_discriminator.rb b/it/ruby/spec/discriminator/integration_test_discriminator.rb new file mode 100644 index 0000000000..ac5b6cc95b --- /dev/null +++ b/it/ruby/spec/discriminator/integration_test_discriminator.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +RSpec.describe Integration_test do + def deserialize(hash) + MicrosoftKiotaSerializationJson::JsonParseNodeFactory.new.get_parse_node("application/json", hash.to_json) + .get_object_value(Integration_test::Client::Discriminateme::Component.method(:create_from_discriminator_value)) + end + + def serialize(value) + writer = MicrosoftKiotaSerializationJson::JsonSerializationWriterFactory.new.get_serialization_writer("application/json") + writer.write_object_value(nil, value) + JSON.parse(writer.get_serialized_content) + end + + it "deserializes the first member of the union" do + result = deserialize("objectType" => "obj1", "one" => "foo") + + expect(result.component2).to be_nil + expect(result.component1).to be_a(Integration_test::Client::Models::Component1) + expect([result.component1.object_type, result.component1.one]).to eq(%w[obj1 foo]) + end + + it "deserializes the second member of the union" do + result = deserialize("objectType" => "obj2", "two" => "bar") + + expect(result.component1).to be_nil + expect(result.component2).to be_a(Integration_test::Client::Models::Component2) + expect([result.component2.object_type, result.component2.two]).to eq(%w[obj2 bar]) + end + + it "serializes the first member of the union" do + component = Integration_test::Client::Discriminateme::Component.new + component.component1 = Integration_test::Client::Models::Component1.new + component.component1.object_type = "obj1" + component.component1.one = "foo" + + expect(serialize(component)).to eq("objectType" => "obj1", "one" => "foo") + end + + it "serializes the second member of the union" do + component = Integration_test::Client::Discriminateme::Component.new + component.component2 = Integration_test::Client::Models::Component2.new + component.component2.object_type = "obj2" + component.component2.two = "bar" + + expect(serialize(component)).to eq("objectType" => "obj2", "two" => "bar") + end +end diff --git a/it/ruby/spec/query-params/integration_test_query_params.rb b/it/ruby/spec/query-params/integration_test_query_params.rb new file mode 100644 index 0000000000..609be9a2d0 --- /dev/null +++ b/it/ruby/spec/query-params/integration_test_query_params.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +RSpec.describe Integration_test do + def uri_with(**query) + client = Integration_test::Client::ApiClient.new(MicrosoftKiotaFaraday::FaradayRequestAdapter.new(MicrosoftKiotaAbstractions::AnonymousAuthenticationProvider.new)) + config = MicrosoftKiotaAbstractions::RequestConfiguration.new + config.query_parameters = Integration_test::Client::Api::Something::V1::V1RequestBuilder::V1RequestBuilderGetQueryParameters.new + query.each { |name, value| config.query_parameters.public_send(:"#{name}=", value) } + request_info = client.api.something.v1.to_get_request_information(config) + request_info.path_parameters["baseurl"] = "http://test" + request_info.uri.to_s + end + + it "includes some query parameter" do + expect(uri_with(start_date_time: "START")).to eq("http://test/api/something/v1?startDateTime=START") + end + + it "includes some other query parameter" do + expect(uri_with(end_date_time: "END")).to eq("http://test/api/something/v1?EndDateTime=END") + end + + it "includes all the query parameters" do + expect(uri_with(start_date_time: "START", end_date_time: "END")).to eq("http://test/api/something/v1?EndDateTime=END&startDateTime=START") + end +end From d9fc9df0c5d1e3c750959cc226eeaf4b6d370fd3 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 14:02:20 +0100 Subject: [PATCH 20/25] test(ruby): run the default spec alongside the mock server specs --- it/exec-cmd.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/it/exec-cmd.ps1 b/it/exec-cmd.ps1 index 375cb60fa2..284e66e1bd 100755 --- a/it/exec-cmd.ps1 +++ b/it/exec-cmd.ps1 @@ -232,12 +232,12 @@ elseif ($language -eq "typescript") { } -ErrorAction Stop } elseif ($language -eq "ruby") { - # Mock server tests are places in a subdir in "spec". So execute them. + # Mock server tests are places in a subdir in "spec". So execute them, with the default test. if ($mockServerTest) { Invoke-call -ScriptBlock { git init bundle install - bundle exec rake SPEC=spec/$mockSeverITFolder/*.rb + bundle exec rake "SPEC=spec/{$mockSeverITFolder/*,integration_test_spec}.rb" } } else { From cef75361872042e06fd1219b57b5cb4ad86a8d1d Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 17:28:22 +0100 Subject: [PATCH 21/25] test(ruby): run the integration tests against the 0.22 runtime gems --- it/ruby/Gemfile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/it/ruby/Gemfile b/it/ruby/Gemfile index ca025efd9d..afe1e6f039 100644 --- a/it/ruby/Gemfile +++ b/it/ruby/Gemfile @@ -11,10 +11,10 @@ gem "rspec", "~> 3.0" gem "rubocop", "~> 1.21" -gem "microsoft_kiota_abstractions", "~> 0.19.0" +gem "microsoft_kiota_abstractions", "~> 0.22.0" -gem "microsoft_kiota_faraday", "~> 0.19.0" +gem "microsoft_kiota_faraday", "~> 0.22.0" -gem "microsoft_kiota_serialization_json", "~> 0.19.0" +gem "microsoft_kiota_serialization_json", "~> 0.22.0" -gem "microsoft_kiota_authentication_oauth", "~> 0.19.0" +gem "microsoft_kiota_authentication_oauth", "~> 0.22.0" From 7352377687f3e68dd1dc888df5ce355a395eefe9 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 18:05:47 +0100 Subject: [PATCH 22/25] test(ruby): check that every constant the generated code names resolves --- it/ruby/spec/integration_test_spec.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/it/ruby/spec/integration_test_spec.rb b/it/ruby/spec/integration_test_spec.rb index 4c94d100e6..d462677eaf 100644 --- a/it/ruby/spec/integration_test_spec.rb +++ b/it/ruby/spec/integration_test_spec.rb @@ -16,4 +16,17 @@ it "eager loads every constant the client registers" do expect { Integration_test::Client.eager_load! }.not_to raise_error end + + it "resolves every constant the generated code names" do + names = Dir[File.expand_path("../lib/integration_test/client/**/*.rb", __dir__)].flat_map do |file| + File.read(file).scan(/Integration_test::Client(?:::[A-Z]\w*)+/) + end + unresolved = names.uniq.reject do |name| + Object.const_get(name) + rescue NameError + false + end + + expect(unresolved).to be_empty + end end From 6c67ec9e907b6007b2cd1e888a317db3505f48a7 Mon Sep 17 00:00:00 2001 From: andreatp Date: Mon, 28 Sep 2026 18:06:24 +0100 Subject: [PATCH 23/25] docs(ruby): correct and complete the changelog entries --- CHANGELOG.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b8be73a808..d4f6074ab7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,10 +17,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Dart: escape enum options named value or values to avoid conflicts with generated and built-in enum members. [#7807](https://github.com/microsoft/kiota/issues/7807) - Ruby: the client's root module has an `eager_load!` method that loads every autoloaded model, for servers that preload before forking. - Ruby: generated files start with `# frozen_string_literal: true`, so string default values handed to user code are frozen. -- Ruby: generated string literals are double quoted, so a base URL, URL template or content type containing a newline or tab now keeps it instead of a literal backslash sequence. +- Ruby: generated string literals are double quoted, the StandardRB convention. - Ruby: namespaces with nothing to autoload no longer get an empty barrel file, and generated files no longer require them (561 fewer files in a GitHub client). - Ruby: a client generated with a multi-segment `--namespace-name`, such as `integration_test.client`, failed to load because its root file was written one directory too deep. -- Ruby: namespace barrels register their models and enums with `autoload` instead of requiring them, so a subclass no longer fails to load when its base class file is required first. Other files require the barrel rather than an individual model file, and models now load on first use. [#7956](https://github.com/microsoft/kiota/issues/7956) +- Ruby: namespace barrels register their models and enums with `autoload` instead of requiring them, so a subclass no longer fails to load when its base class file is required first. Other files require the barrel rather than an individual model file, and models now load on first use. A type no barrel autoloads, such as a model named after its namespace, is now required directly: 1,315 constants referenced by a Meraki client never loaded, and a client generated from the current GitHub description failed to load because it required a file that is never written. [#7956](https://github.com/microsoft/kiota/issues/7956) +- Ruby: model properties are declared with `attr_accessor`, which removes the thousands of "possibly useless use of a variable" warnings `ruby -w` printed while loading a client. +- Ruby: enum hashes are frozen. [kiota-ruby#68](https://github.com/microsoft/kiota-ruby/issues/68) - C#: escape Unicode line and paragraph separators in generated string literals so generated clients remain valid C# source. - External reference allowlist wildcards no longer cross the URI authority boundary, so a wildcard in the scheme or host cannot match text in the path, the user information or the port. - Initialize inherited Dart model fields in constructor initializer lists. From 760efc270ea85875810c16b29eecbef3354390c7 Mon Sep 17 00:00:00 2001 From: andreatp Date: Tue, 29 Sep 2026 11:08:30 +0100 Subject: [PATCH 24/25] test(ruby): stop excluding GitHub's contents endpoint, which now loads --- it/config.json | 5 ----- 1 file changed, 5 deletions(-) diff --git a/it/config.json b/it/config.json index af76a736d8..880c24aebf 100644 --- a/it/config.json +++ b/it/config.json @@ -27,11 +27,6 @@ "Language": "typescript", "Pattern": "/repos/{owner}/{repo}/contents/{path}#GET", "Rationale": "Kiota fails for typescript with api version 1.1.4 dated 2026-06-17 - https://github.com/microsoft/kiota/issues/7803" - }, - { - "Language": "ruby", - "Pattern": "/repos/{owner}/{repo}/contents/{path}#GET", - "Rationale": "The oneOf response leaves a model detached from the DOM while a using still references it, so the composed type wrapper requires a file that is never generated. Same endpoint excluded for Java and TypeScript - https://github.com/microsoft/kiota/issues/7829" } ] }, From b77d120359f5a16bdd1e023d98f9f2cc45add96c Mon Sep 17 00:00:00 2001 From: andreatp Date: Tue, 29 Sep 2026 11:50:27 +0100 Subject: [PATCH 25/25] fix(ruby): repeat the eager_load! walk until a pass loads nothing new - the Ruby IT checks that no autoload is left pending after eager_load! --- it/ruby/spec/integration_test_spec.rb | 15 ++++++++++++++- .../Writers/Ruby/CodeNamespaceWriter.cs | 8 ++++++-- .../Writers/Ruby/CodeNamespaceWriterTests.cs | 1 + 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/it/ruby/spec/integration_test_spec.rb b/it/ruby/spec/integration_test_spec.rb index d462677eaf..87656067fe 100644 --- a/it/ruby/spec/integration_test_spec.rb +++ b/it/ruby/spec/integration_test_spec.rb @@ -14,7 +14,20 @@ # models are autoloaded, so a bad registration only fails when the constant is first used it "eager loads every constant the client registers" do - expect { Integration_test::Client.eager_load! }.not_to raise_error + Integration_test::Client.eager_load! + unloaded = [] + pending = [Integration_test::Client] + until pending.empty? + mod = pending.pop + mod.constants(false).each do |name| + next unloaded << "#{mod}::#{name}" if mod.autoload?(name, false) + + value = mod.const_get(name, false) + pending << value if value.instance_of?(Module) + end + end + + expect(unloaded).to be_empty end it "resolves every constant the generated code names" do diff --git a/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs index b7fbd164ef..c8ba8bcb49 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeNamespaceWriter.cs @@ -45,15 +45,19 @@ private static void WriteEagerLoad(LanguageWriter writer) RubyConventionService.WriteMemberSeparator(writer); writer.WriteLine("# Loads every model and enum registered for autoload, for example before a server forks."); writer.StartBlock("def self.eager_load!"); - writer.WriteLines("pending = [self]", "seen = {}"); + // a loaded file can register autoloads in a module already walked, so walk again until nothing loads + writer.StartBlock("loop do"); + writer.WriteLines("loaded = false", "pending = [self]", "seen = {}"); writer.StartBlock("until pending.empty?"); writer.WriteLines("mod = pending.pop", "next if seen.key?(mod)"); writer.WriteLine(); writer.WriteLine("seen[mod] = true"); writer.StartBlock("mod.constants(false).each do |name|"); - writer.WriteLines("value = mod.const_get(name, false)", "pending << value if value.instance_of?(::Module)"); + writer.WriteLines("loaded = true if mod.autoload?(name, false)", "value = mod.const_get(name, false)", "pending << value if value.instance_of?(::Module)"); writer.CloseBlock("end"); writer.CloseBlock("end"); + writer.WriteLine("break unless loaded"); + writer.CloseBlock("end"); writer.CloseBlock("end"); } } diff --git a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs index 83f30104ba..7fa8812a21 100644 --- a/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Ruby/CodeNamespaceWriterTests.cs @@ -59,6 +59,7 @@ public void WritesEagerLoadInTheClientNamespaceEvenWithNothingToAutoload() var result = tw.ToString(); Assert.Contains("def self.eager_load!", result, StringComparison.Ordinal); Assert.Contains("instance_of?(::Module)", result, StringComparison.Ordinal); + Assert.Contains("break unless loaded", result, StringComparison.Ordinal); Assert.Contains("module Graph", result, StringComparison.Ordinal); } [Fact]