Search code examples
rubyamazon-s3fog

How to list all files in an S3 folder using Fog in Ruby


How do I list all the files in a specific S3 "directory" using Fog?

I know that S3 doesn't store files in folders but I need a way to limit the returned files to specific "folder" instead of retrieving the entire list in the bucket.


Solution

  • Use the prefix option on the directory.get method. Example:

    def get_files(path, options)
      connection = Fog::Storage.new(
        provider: 'AWS',
        aws_access_key_id: options[:key],
        aws_secret_access_key: options[:secret]
      )
      connection.directories.get(options[:bucket], prefix: path).files.map do |file|
        file.key
      end
    end