Skip to content

Commit c2fc39e

Browse files
authored
Avoid double newlines when appending to a file (#14)
1 parent a2ef4d8 commit c2fc39e

2 files changed

Lines changed: 22 additions & 4 deletions

File tree

lib/dry/files.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -933,6 +933,8 @@ def initialize(name, opening, closing)
933933
# @since 0.1.0
934934
# @api private
935935
def newline(line = nil)
936+
return line if line.to_s.end_with?(NEW_LINE)
937+
936938
"#{line}#{NEW_LINE}"
937939
end
938940

spec/integration/dry/files_spec.rb

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -494,10 +494,26 @@ class Append
494494
expect(path).to have_content(expected)
495495
end
496496

497-
# This gem was originally extracted from hanami-utils, into dry-cli,
498-
# and finally into dry-files.
499-
#
500-
# https://github.com/hanami/utils/issues/348
497+
it "does not add multiple newlines to the bottom of the file" do
498+
path = root.join("append.rb")
499+
content = <<~CONTENT
500+
class Append
501+
end
502+
CONTENT
503+
504+
subject.write(path, content)
505+
subject.append(path, "#{newline}Foo.register Append\n")
506+
507+
expected = <<~CONTENT
508+
class Append
509+
end
510+
511+
Foo.register Append
512+
CONTENT
513+
514+
expect(path).to have_content(expected)
515+
end
516+
501517
it "adds a line at the bottom of a file that doesn't end with a newline" do
502518
path = root.join("append_missing_newline.rb")
503519
content = "root to: 'home#index'"

0 commit comments

Comments
 (0)