Reputation: 47
I'm new to AWS and I'm trying to loop through my bucket objects to generate urls to read the objects. I found the following reference in the AWS documentation:
bucket.objects.myobject.url_for(:read)
I have the following method which contains a loop that can at least print the key for each object BUT I'm struggling to get the url_for to work. Any ideas?
def aws_s3_url
s3_client = Aws::S3::Resource.new(region: ENV['AWS_REGION'])
bucket = s3_client.bucket(ENV['S3_BUCKET'])
bucket.objects.each do |name|
puts name.key
end
end
All help is appreciated.
Upvotes: 0
Views: 608
Reputation: 2912
I don't know the specific use-case you have, but you don't need the URL to read the objects in the bucket since the AWS SDK maps the files in the bucket to instances of Object.
To read the contents of the file, try this:
@s3_client = Aws::S3::Resource.new(region: ENV['AWS_REGION'])
def file_content(key)
bucket = @s3_client.bucket(ENV['S3_BUCKET'])
obj = @s3_client.get_object(bucket: bucket, key: key)
obj.body.read
end
def get_all_files
bucket = @s3_client.bucket(ENV['S3_BUCKET'])
bucket.objects.each do |o|
puts file_content(o.key)
end
end
To return the public URL for the object, you can try:
def get_url(key)
bucket = @s3_client.bucket(ENV['S3_BUCKET'])
obj = @s3_client.get_object(bucket: bucket, key: key)
obj.public_url
end
Upvotes: 1