简体   繁体   English

AWS S3 Ruby SDK V2中的as_tree

[英]as_tree in AWS S3 Ruby SDK V2

In v1 the AWS S3 sdk there was a method called "as_tree" that you could call on a list of objects, and it would return it in a nice Branch/Leaf format that made it easy to traverse. 在v1 AWS S3 sdk中,有一个称为“ as_tree”的方法,您可以在对象列表上调用它,并且它将以一种很好的Branch / Leaf格式返回它,从而使其易于遍历。 I can't find anything in the docs for v2 for a method like this. 对于这种方法,我在v2 的文档中找不到任何内容。 Is there any way to do this in v2? 在v2中有什么方法可以做到这一点?

If not, how can I replicate a similar functionality in v2? 如果没有,如何在v2中复制类似的功能? I'm fine with writing a new method to create a tree and modifying my code a bit. 我可以编写一种新方法来创建树并稍加修改我的代码。

Thanks a comment from George M Whitaker gave me a method that would return some of the data I needed. 感谢George M Whitaker的评论,这给了我一种方法,该方法可以返回我需要的一些数据。 I used this to create my own version of as_tree, so I'll post that here. 我用它来创建自己的as_tree版本,因此将其发布在这里。

class S3Node 
end

class S3Leaf < S3Node
  attr_accessor :object
  attr_accessor :key

  def leaf? 
    true
  end

  def branch?
    false
  end

  def initialize(summary)
    @key = summary.key
    @object = S3_BUCKET.object(@key)
  end
end

class S3Tree < S3Node
  attr_accessor :children
  attr_accessor :prefix

  def leaf? 
    false
  end

  def branch?
    true
  end

  def initialize(options) 
    @prefix = options[:prefix]

    @resp = S3_CLIENT.list_objects_v2(bucket: S3_BUCKET.name, prefix: @prefix, delimiter: '/')
    @common_prefixes = @resp.common_prefixes
    @contents = @resp.contents

    @trees = @common_prefixes.map do |common_prefix|
      S3Tree.new(prefix: common_prefix.prefix)
    end

    @leaves = @contents.select { |content| content.key.length > @prefix.length }.map do |content|
      S3Leaf.new(content)
    end

    @children = @trees + @leaves
  end
end

Thus you can call S3Tree.new(prefix: 'your/prefix/here') instead of S3_BUCKET.as_tree(prefix: 'your/prefix/here'), and you should have most of the functionality of the old as_tree. 因此,您可以调用S3Tree.new(prefix:'your / prefix / here')而不是S3_BUCKET.as_tree(prefix:'your / prefix / here'),并且您应该具有旧as_tree的大部分功能。 In my code I have constatns S3_BUCKET and S3_CLIENT, so you'll need to replace these with your own buckets and clients. 在我的代码中,我的状态为S3_BUCKET和S3_CLIENT,因此您需要用自己的存储桶和客户端替换它们。 Here's the code I use to initialze those if anyone is wondering. 如果有人在想的话,这是我用来初始化这些代码的代码。

S3_RESOURCE = Aws::S3::Resource.new
S3_CLIENT = Aws::S3::Client.new

S3_BUCKET = S3_RESOURCE.bucket(ENV['BUCKET_NAME'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM