Skip to content

Commit

Permalink
Avoid double newlines when appending to a file (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
timriley committed Nov 21, 2022
1 parent a2ef4d8 commit c2fc39e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
2 changes: 2 additions & 0 deletions lib/dry/files.rb
Expand Up @@ -933,6 +933,8 @@ def initialize(name, opening, closing)
# @since 0.1.0
# @api private
def newline(line = nil)
return line if line.to_s.end_with?(NEW_LINE)

"#{line}#{NEW_LINE}"
end

Expand Down
24 changes: 20 additions & 4 deletions spec/integration/dry/files_spec.rb
Expand Up @@ -494,10 +494,26 @@ class Append
expect(path).to have_content(expected)
end

# This gem was originally extracted from hanami-utils, into dry-cli,
# and finally into dry-files.
#
# https://github.com/hanami/utils/issues/348
it "does not add multiple newlines to the bottom of the file" do
path = root.join("append.rb")
content = <<~CONTENT
class Append
end
CONTENT

subject.write(path, content)
subject.append(path, "#{newline}Foo.register Append\n")

expected = <<~CONTENT
class Append
end
Foo.register Append
CONTENT

expect(path).to have_content(expected)
end

it "adds a line at the bottom of a file that doesn't end with a newline" do
path = root.join("append_missing_newline.rb")
content = "root to: 'home#index'"
Expand Down

0 comments on commit c2fc39e

Please sign in to comment.