diff --git a/ext/rfmt/src/emitter/mod.rs b/ext/rfmt/src/emitter/mod.rs index 02c430b..5e4646e 100644 --- a/ext/rfmt/src/emitter/mod.rs +++ b/ext/rfmt/src/emitter/mod.rs @@ -1196,6 +1196,16 @@ impl Emitter { if let Some(text) = self.source.get(start..end) { // Trim trailing whitespace but preserve the content write!(self.buffer, "{}", text.trim_end())?; + + // Mark comments within the extracted range as emitted + for (idx, comment) in self.all_comments.iter().enumerate() { + if !self.emitted_comment_indices.contains(&idx) + && comment.location.start_offset >= start + && comment.location.end_offset <= end + { + self.emitted_comment_indices.insert(idx); + } + } } } diff --git a/spec/rfmt_spec.rb b/spec/rfmt_spec.rb index 36220ee..9a3a470 100644 --- a/spec/rfmt_spec.rb +++ b/spec/rfmt_spec.rb @@ -253,6 +253,33 @@ def bar = 42 source = "[1, 2].map { |x| x * 2 } # double\n" expect(Rfmt.format(source)).to eq("[1, 2].map { |x| x * 2 } # double\n") end + + it 'does not duplicate inline comments on method chain with block' do + source = <<~RUBY + some_method # comment + .method_with_block { do_something } + RUBY + + result = Rfmt.format(source) + + # The comment should appear exactly once, not be duplicated + expect(result.scan('# comment').count).to eq(1) + expect(result).to eq(source) + end + + it 'does not duplicate inline comments on method chain with do-end block' do + source = <<~RUBY + some_method # comment + .method_with_block do + do_something + end + RUBY + + result = Rfmt.format(source) + + # The comment should appear exactly once + expect(result.scan('# comment').count).to eq(1) + end end end