diff --git a/CHANGELOG.md b/CHANGELOG.md index 5df9dd1..f5b1577 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +v0.4.0 +------ +- Add an `.exists?` method that returns `true`/`false` depending on whether a given + key exists or not. + v0.3.0 ------ - Add support for S3 diff --git a/lib/bucket_store/key_storage.rb b/lib/bucket_store/key_storage.rb index 36e1b77..90bedf5 100644 --- a/lib/bucket_store/key_storage.rb +++ b/lib/bucket_store/key_storage.rb @@ -143,6 +143,19 @@ def delete! true end + # Checks if the given key exists. + # + # This will only return true when the `key` exactly matches an object within the bucket + # and conversely it will return false when `key` matches an internal path to an object. + # For example if the bucket has a key named `prefix/file.txt`, it will only return + # `true` when `exists?` is called on `prefix/file.txt`. Any other combination + # (`prefix/`, `prefix/file`) will instead return `false`. + # + # @return [bool] `true` if the given key exists, `false` if not + def exists? + list.first == "#{adapter_type}://#{bucket}/#{key}" + end + private attr_reader :adapter diff --git a/lib/bucket_store/version.rb b/lib/bucket_store/version.rb index bf2bdf7..b3f98c9 100644 --- a/lib/bucket_store/version.rb +++ b/lib/bucket_store/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module BucketStore - VERSION = "0.3.0" + VERSION = "0.4.0" end diff --git a/spec/bucket_store/key_storage_spec.rb b/spec/bucket_store/key_storage_spec.rb index a2147a0..c41f65e 100644 --- a/spec/bucket_store/key_storage_spec.rb +++ b/spec/bucket_store/key_storage_spec.rb @@ -117,7 +117,7 @@ def build_for(key) end end - describe "delete!" do + describe "#delete!" do before do build_for("inmemory://bucket/file1").upload!("content1") end @@ -126,4 +126,32 @@ def build_for(key) expect(build_for("inmemory://bucket/file1").delete!).to eq(true) end end + + describe "#exists?" do + before do + build_for("inmemory://bucket/file").upload!("content1") + build_for("inmemory://bucket/prefix/another_file").upload!("content2") + end + + it "returns false when a key does not exist" do + expect(build_for("inmemory://bucket/invalid").exists?).to be false + expect(build_for("inmemory://invalid_bucket/file").exists?).to be false + end + + it "returns true when a key exists" do + expect(build_for("inmemory://bucket/file").exists?).to be true + expect(build_for("inmemory://bucket/prefix/another_file").exists?).to be true + end + + it "returns false when a key matches a path" do + expect(build_for("inmemory://bucket").exists?).to be false + expect(build_for("inmemory://bucket/").exists?).to be false + expect(build_for("inmemory://bucket/prefix/").exists?).to be false + end + + it "returns false when a key only partially matches a file name" do + expect(build_for("inmemory://bucket/f").exists?).to be false + expect(build_for("inmemory://bucket/prefix/a").exists?).to be false + end + end end