From f26f250219f9dd9b549d2ef79fb5d8a011eb6913 Mon Sep 17 00:00:00 2001 From: Vladimir Kochnev Date: Fri, 17 Jan 2025 01:13:11 +0300 Subject: [PATCH] Support nested structs of the form A::B = Struct.new(...) --- lib/yard/handlers/ruby/constant_handler.rb | 6 +++--- spec/handlers/constant_handler_spec.rb | 11 +++++++++++ spec/handlers/examples/constant_handler_001.rb.txt | 1 + 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/lib/yard/handlers/ruby/constant_handler.rb b/lib/yard/handlers/ruby/constant_handler.rb index d90504c6b..a7b10b407 100644 --- a/lib/yard/handlers/ruby/constant_handler.rb +++ b/lib/yard/handlers/ruby/constant_handler.rb @@ -31,9 +31,9 @@ def process_constant(statement) end def process_structclass(statement) - lhs = statement[0][0] - if lhs.type == :const - klass = create_class(lhs[0], P(:Struct)) + lhs = statement[0] + if (lhs.type == :var_field && lhs[0].type == :const) || lhs.type == :const_path_field + klass = create_class(lhs.source, P(:Struct)) create_attributes(klass, extract_parameters(statement[1])) parse_block(statement[1].block[1], :namespace => klass) unless statement[1].block.nil? else diff --git a/spec/handlers/constant_handler_spec.rb b/spec/handlers/constant_handler_spec.rb index 8d2643e24..d97d58729 100644 --- a/spec/handlers/constant_handler_spec.rb +++ b/spec/handlers/constant_handler_spec.rb @@ -57,6 +57,17 @@ expect(obj.attributes[:instance]).to be_empty end + it "turns A::Const = Struct.new(:sym) into class A::Const with attr :sym" do + obj = Registry.at("A::NestedCompactClass") + expect(obj).to be_kind_of(CodeObjects::ClassObject) + attrs = obj.attributes[:instance] + [:b, :c].each do |key| + expect(attrs).to have_key(key) + expect(attrs[key][:read]).not_to be nil + expect(attrs[key][:write]).not_to be nil + end + end + it "maintains docstrings on structs defined via constants" do obj = Registry.at("DocstringStruct") expect(obj).not_to be nil diff --git a/spec/handlers/examples/constant_handler_001.rb.txt b/spec/handlers/examples/constant_handler_001.rb.txt index 1d93263a7..bc69c854f 100644 --- a/spec/handlers/examples/constant_handler_001.rb.txt +++ b/spec/handlers/examples/constant_handler_001.rb.txt @@ -17,6 +17,7 @@ end MyClass = Struct.new(:a, :b, :c) NotMyClass = Struct.new("NotMyClass2", :b, :c) MyEmptyStruct = Struct.new +A::NestedCompactClass = Struct.new(:b, :c) MyStructWithConstant = Struct.new do # A constant.