Module: S3Utils::Method

Included in:
S3Utils
Defined in:
lib/s3_utils/method.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



5
6
7
# File 'lib/s3_utils/method.rb', line 5

def self.included(klass)
  klass.extend(self)
end

Instance Method Details

#copy_on_s3(src, dest) ⇒ Object



56
57
58
59
60
61
# File 'lib/s3_utils/method.rb', line 56

def copy_on_s3(src, dest)
  gs = Generator.new(src)
  gd = Generator.new(dest)

  gs.s3_object.copy_to(gd.s3_object)
end

#create_on_s3(path) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/s3_utils/method.rb', line 68

def create_on_s3(path)
  @tmp = Tempfile.new('')
  g = Generator.new(path)

  File.open(@tmp, "w") do |f|
    yield f if block_given?
  end

  g.s3_object.write(file: @tmp.path)
ensure
  @tmp.close! if @tmp
end

#delete_on_s3(path) ⇒ Object



63
64
65
66
# File 'lib/s3_utils/method.rb', line 63

def delete_on_s3(path)
  g = Generator.new(path)
  g.s3_object.delete
end

#download_from_s3(src, dest) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/s3_utils/method.rb', line 28

def download_from_s3(src, dest)
  g = Generator.new(src)

  if g.s3_object.exists?
    download_path = File.directory?(dest) ? File.join(dest, File.basename(src)) : dest
    File.open(download_path, 'w') do |f|
      g.s3_object.read { |chunk| f.write(chunk) }
    end
  else
    file_objects = g.tree.children(&:reaf?).map(&:object)

    file_objects.each do |obj|
      next unless obj.exists?

      base_dir = File.basename(File.dirname(obj.key))
      obj_name = File.basename(obj.key)

      unless Dir.exist?(File.join(dest, base_dir))
        Dir.mkdir(File.join(dest, base_dir))
      end

      File.open(File.join(dest, base_dir, obj_name), 'w') do |f|
        obj.read { |chunk| f.write(chunk) }
      end
    end
  end
end

#read_on_s3(path) ⇒ Object



81
82
83
84
# File 'lib/s3_utils/method.rb', line 81

def read_on_s3(path)
  g = Generator.new(path)
  g.s3_object.read.chomp
end

#upload_to_s3(src, dest) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/s3_utils/method.rb', line 9

def upload_to_s3(src, dest)
  g = Generator.new(dest)

  case
  when File.file?(src)
    filename = File.basename(src.to_s) if dest.to_s.end_with?('/')
    g.s3_object(filename).write(file: src)
  when File.directory?(src)
    Dir[File.join(src, '**', '*')].each do |path|
      next if File.directory?(path)
      g.s3_object(path).write(file: path)
    end
  else
    Dir[src].each do |path|
      g.s3_object(path).write(file: path)
    end
  end
end