diff --git a/lib/dry/files/error.rb b/lib/dry/files/error.rb index 7ec617d..0ea653d 100644 --- a/lib/dry/files/error.rb +++ b/lib/dry/files/error.rb @@ -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 diff --git a/lib/dry/files/file_system.rb b/lib/dry/files/file_system.rb index 235f3ce..9c46a1b 100644 --- a/lib/dry/files/file_system.rb +++ b/lib/dry/files/file_system.rb @@ -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| diff --git a/lib/dry/files/memory_file_system/node.rb b/lib/dry/files/memory_file_system/node.rb index f464e17..8a9715b 100644 --- a/lib/dry/files/memory_file_system/node.rb +++ b/lib/dry/files/memory_file_system/node.rb @@ -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 diff --git a/spec/unit/dry/files/file_system_spec.rb b/spec/unit/dry/files/file_system_spec.rb index 664d1d9..ad7ef4f 100644 --- a/spec/unit/dry/files/file_system_spec.rb +++ b/spec/unit/dry/files/file_system_spec.rb @@ -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 diff --git a/spec/unit/dry/files/memory_file_system_spec.rb b/spec/unit/dry/files/memory_file_system_spec.rb index 228646c..961fe5f 100644 --- a/spec/unit/dry/files/memory_file_system_spec.rb +++ b/spec/unit/dry/files/memory_file_system_spec.rb @@ -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