Skip to content

Commit

Permalink
Extract CanOnlyWriteStrings Error
Browse files Browse the repository at this point in the history
  • Loading branch information
cllns committed Jan 21, 2022
1 parent f41b906 commit f3bd6fc
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 1 deletion.
18 changes: 18 additions & 0 deletions lib/dry/files/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,5 +116,23 @@ def initialize(path)
super("not a memory file `#{path}'")
end
end

# Can only write strings (i.e. not arrays, or anything else)
#
# Raised by the file system adapters
#
# @since x.x.x
# @api public
class CanOnlyWriteStringsError < Error
# Instantiate a new error
#
# @param path [String] path name
#
# @since x.x.x
# @api public
def initialize
super("Can only write strings (use `String#join` or `String#to_s`?)")
end
end
end
end
2 changes: 2 additions & 0 deletions lib/dry/files/file_system.rb
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ def touch(path, **kwargs)
# @since 0.1.0
# @api private
def write(path, content)
raise CanOnlyWriteStringsError unless content.is_a?(String)

mkdir_p(path)

self.open(path, WRITE_MODE) do |f|
Expand Down
3 changes: 2 additions & 1 deletion lib/dry/files/memory_file_system/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,8 @@ def readlines
# @since 0.1.0
# @api private
def write(content)
raise ArgumentError, "Join your content before trying to write it" unless content.is_a?(String)
raise CanOnlyWriteStringsError unless content.is_a?(String)

@content = StringIO.new(content)
@mode = DEFAULT_FILE_MODE
end
Expand Down
6 changes: 6 additions & 0 deletions spec/unit/dry/files/file_system_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,12 @@
path.chmod(mode)
end
end

it "raises error when trying to write a non-string" do
path = root.join("write")
expect { subject.write(path, %w[hello world]) }
.to raise_error(Dry::Files::CanOnlyWriteStringsError)
end
end

describe "#join" do
Expand Down
6 changes: 6 additions & 0 deletions spec/unit/dry/files/memory_file_system_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,12 @@
path.chmod(mode)
end
end

it "raises error when trying to write a non-string" do
path = subject.join("write")
expect { subject.write(path, %w[hello world]) }
.to raise_error(Dry::Files::CanOnlyWriteStringsError)
end
end

describe "#join" do
Expand Down

0 comments on commit f3bd6fc

Please sign in to comment.