Class: Tools::S3Storage
- Inherits:
-
Object
- Object
- Tools::S3Storage
- Defined in:
- lib/tools/s3_storage.rb
Instance Method Summary collapse
-
#download(file_name) ⇒ Object
Create a local file with the contents of the remote file.
-
#initialize(configuration) ⇒ S3Storage
constructor
A new instance of S3Storage.
-
#list_files ⇒ Object
List all the files in the bucket’s remote path.
-
#upload(file_path, tags = '') ⇒ Object
Send files to S3.
Constructor Details
#initialize(configuration) ⇒ S3Storage
Returns a new instance of S3Storage.
9 10 11 12 13 14 15 16 17 |
# File 'lib/tools/s3_storage.rb', line 9 def initialize(configuration) @configuration = configuration @s3 = Fog::Storage.new( provider: 'AWS', region: configuration.region, aws_access_key_id: configuration.aws_access_key_id, aws_secret_access_key: configuration.aws_secret_access_key ) end |
Instance Method Details
#download(file_name) ⇒ Object
Create a local file with the contents of the remote file.
The new file will be saved in the ‘backup_folder` that was set in the configuration (the default value is `db/backups`)
62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/tools/s3_storage.rb', line 62 def download(file_name) remote_file_path = File.join(remote_path, file_name) local_file_path = File.join(backup_folder, file_name) file_from_storage = remote_directory.files.get(remote_file_path) prepare_local_folder(local_file_path) create_local_file(local_file_path, file_from_storage) local_file_path end |
#list_files ⇒ Object
List all the files in the bucket’s remote path. The result is sorted in the reverse order, the most recent file will show up first.
Return an array of strings, containing only the file name.
46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/tools/s3_storage.rb', line 46 def list_files files = remote_directory.files.map { |file| file.key } # The first item in the array is only the path an can be discarded. files = files.slice(1, files.length - 1) || [] files .map { |file| Pathname.new(file).basename.to_s } .sort .reverse end |
#upload(file_path, tags = '') ⇒ Object
Send files to S3.
To test this, go to the console and execute:
“‘ file_path = “#Rails.root/Gemfile” S3Storage.new.upload(file_path) “`
It will send the Gemfile to S3, inside the ‘remote_path` set in the configuration. The bucket name and the credentials are also read from the configuration.
31 32 33 34 35 36 37 38 39 |
# File 'lib/tools/s3_storage.rb', line 31 def upload(file_path, = '') file_name = Pathname.new(file_path).basename remote_file.create( key: File.join(remote_path, file_name), body: File.open(file_path), tags: ) end |