Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid double newlines when appending to a file #14

Merged
merged 1 commit into from Nov 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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