Amazon AWS: How to replicate tree/branch functionality from AWS Ruby SDK v1 in AWS Ruby SDK v2?

老子叫甜甜 提交于 2020-01-02 08:25:02

问题


In version 1 of their SDK, Amazon provided some really useful methods that could be used to explore the contents of buckets using Tree, ChildCollection, LeafNode, BranchNode, etc. Unfortunately, I've had a difficulty time replicating their functionality with version 2 of the SDK, which doesn't seem to include such methods. Ideally, I'd like to do something similar to the example below, which is taken from the v1 SDK.

tree = bucket.as_tree

directories = tree.children.select(&:branch?).collect(&:prefix)
#=> ['photos', 'videos']

files = tree.children.select(&:leaf?).collect(&:key)
#=> ['README.txt']

Any ideas on how one might achieve this?


回答1:


The tree and branch functionality work by listing objects in a bucket with a prefix and delimiter.The prefix specifies the current "folder" and the delimiter should be a '/' to prevent nested keys from being returned.

For example, to list all of the "files" and "folders" inside the "photos/family/" folder of a bucket:

s3 = Aws::S3::Client.new
resp = s3.list_objects(bucket:'bucket-name', prefix:'photos/family/', delimiter:'/')

# the list of "files"
resp.contents.map(&:key)
#=> ['photos/family/summer_vacation.jpg', 'photos/family/parents.jpg']

# the list of "folders"
resp.common_prefixes
#=> ['photos/family/portraits/', 'photos/family/disney_land/']

The contents are the files, or leaf nodes in a response. The common_prefixes are the directories. If you want to continue down to see the files and folder inside "photos/family/portraits/", then just #list_objects again with a different prefix:

resp = s3.list_objects(bucket:'bucket-name', prefix:'photos/family/portraits/', delimiter:'/')


来源:https://stackoverflow.com/questions/29284946/amazon-aws-how-to-replicate-tree-branch-functionality-from-aws-ruby-sdk-v1-in-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!