Class: RailsArchiver::Transport::S3

Inherits:
Base
  • Object
show all
Defined in:
lib/rails-archiver/transport/s3.rb

Instance Method Summary collapse

Methods inherited from Base

#configure, #initialize

Constructor Details

This class inherits a constructor from RailsArchiver::Transport::Base

Instance Method Details

#gunzip(filename) ⇒ Object



23
24
25
26
27
# File 'lib/rails-archiver/transport/s3.rb', line 23

def gunzip(filename)
  output = `gunzip --force #{filename.shellescape} 2>&1`

  raise output if $?.exitstatus != 0
end

#gzip(filename) ⇒ Object

Gzips the file, returns the gzipped filename



15
16
17
18
19
20
21
# File 'lib/rails-archiver/transport/s3.rb', line 15

def gzip(filename)
  output = `gzip #{filename.shellescape} 2>&1`

  raise output if $?.exitstatus != 0

  "#{filename}.gz"
end

#retrieve_archive(location = nil) ⇒ Object

Parameters:

  • location (String) (defaults to: nil)


50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/rails-archiver/transport/s3.rb', line 50

def retrieve_archive(location=nil)
  Dir.mktmpdir do |dir|
    s3_key = location
    filename = nil
    if @model
      if @model.respond_to?(:archived_s3_key)
        s3_key ||= @model.archived_s3_key
      end
      filename = "#{dir}/#{@model.id}.json"
    else
      filename = File.basename(s3_key)
    end
    _get_archive_from_s3(s3_key, "#{filename}.gz")
    @logger.info('Unzipping file')
    gunzip("#{filename}.gz")
    @logger.info('Parsing JSON')
    JSON.parse(File.read(filename))
  end
end

#s3_clientObject



9
10
11
12
# File 'lib/rails-archiver/transport/s3.rb', line 9

def s3_client
  option_hash = @options[:region] ? {:region => @options[:region]} : {}
  Aws::S3::Client.new(option_hash)
end

#store_archive(hash) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rails-archiver/transport/s3.rb', line 29

def store_archive(hash)
  json = hash.to_json
  file_path = "#{@model.id}_#{SecureRandom.hex(8)}.json"
  base_path = @options[:base_path] ? "#{@options[:base_path]}/" : ''
  s3_key = "#{base_path}#{file_path}.gz"
  Dir.mktmpdir do |dir|
    json_filename = "#{dir}/#{file_path}"
    @logger.info('Writing hash to JSON')
    File.write(json_filename, json)
    @logger.info('Zipping file')
    filename = gzip(json_filename)
    @logger.info("Uploading file to #{s3_key}")
    _save_archive_to_s3(s3_key, filename)
  end
  if @model.respond_to?(:archived_s3_key)
    @model.update_attribute(:archived_s3_key, s3_key)
  end
  s3_key
end