Class: S3CacheStore::S3Client
- Inherits:
-
Object
- Object
- S3CacheStore::S3Client
- Defined in:
- lib/s3_cache_store/s3_client.rb
Instance Attribute Summary collapse
-
#bucket ⇒ Object
readonly
Returns the value of attribute bucket.
Instance Method Summary collapse
- #clear(prefix = "") ⇒ Object
- #delete_object(key) ⇒ Object
- #exists_object?(key) ⇒ Boolean
-
#initialize(bucket:, region: ENV["AWS_REGION"] || ENV["AWS_DEFAULT_REGION"]) ⇒ S3Client
constructor
A new instance of S3Client.
- #list_objects(prefix) ⇒ Object
- #read_object(key) ⇒ Object
- #write_object(key, payload) ⇒ Object
Constructor Details
#initialize(bucket:, region: ENV["AWS_REGION"] || ENV["AWS_DEFAULT_REGION"]) ⇒ S3Client
Returns a new instance of S3Client.
10 11 12 13 14 15 16 17 18 |
# File 'lib/s3_cache_store/s3_client.rb', line 10 def initialize(bucket:, region: ENV["AWS_REGION"] || ENV["AWS_DEFAULT_REGION"]) @bucket = bucket if @bucket.nil? || @bucket.empty? raise ArgumentError, "Bucket name not specified" end @client = Aws::S3::Client.new(region: region) end |
Instance Attribute Details
#bucket ⇒ Object (readonly)
Returns the value of attribute bucket.
8 9 10 |
# File 'lib/s3_cache_store/s3_client.rb', line 8 def bucket @bucket end |
Instance Method Details
#clear(prefix = "") ⇒ Object
56 57 58 59 60 |
# File 'lib/s3_cache_store/s3_client.rb', line 56 def clear(prefix = "") @client.list_objects_v2(bucket: bucket, prefix: prefix).contents.each do |object| @client.delete_object(bucket: bucket, key: object.key) end end |
#delete_object(key) ⇒ Object
39 40 41 42 43 44 45 46 47 |
# File 'lib/s3_cache_store/s3_client.rb', line 39 def delete_object(key) @client.delete_object(bucket: bucket, key: key) if exists_object?(key) true rescue => e # Just in case the error was caused by another process deleting the file first. raise e if exists_object?(key) false end |
#exists_object?(key) ⇒ Boolean
49 50 51 52 53 54 |
# File 'lib/s3_cache_store/s3_client.rb', line 49 def exists_object?(key) @client.head_object(bucket: bucket, key: key) true rescue Aws::S3::Errors::NoSuchKey, Aws::S3::Errors::NotFound false end |
#list_objects(prefix) ⇒ Object
62 63 64 |
# File 'lib/s3_cache_store/s3_client.rb', line 62 def list_objects(prefix) @client.list_objects_v2(bucket: bucket, prefix: prefix).contents end |
#read_object(key) ⇒ Object
20 21 22 23 24 |
# File 'lib/s3_cache_store/s3_client.rb', line 20 def read_object(key) return unless exists_object?(key) @client.get_object(bucket: bucket, key: key).body.read end |
#write_object(key, payload) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/s3_cache_store/s3_client.rb', line 26 def write_object(key, payload) if payload.is_a?(String) || payload.is_a?(File) @client.put_object(bucket: bucket, key: key, body: payload) else Tempfile.open do |f| f.write(payload) f.rewind @client.put_object(bucket: bucket, key: key, body: f) end end true end |