Class: Filer::S3

Inherits:
Object
  • Object
show all
Defined in:
lib/filer/s3.rb

Instance Method Summary collapse

Constructor Details

#initialize(key, secret, bucket_name) ⇒ S3

Returns a new instance of S3.



7
8
9
# File 'lib/filer/s3.rb', line 7

def initialize(key, secret, bucket_name)
  @key, @secret, @bucket_name = key, secret, bucket_name
end

Instance Method Details

#bucketObject



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/filer/s3.rb', line 20

def bucket
  return @bucket if @bucket 
  bucket = s3.buckets[@bucket_name]
  unless bucket.location_constraint == s3.config.region
    @s3 = nil
    @s3 = AWS::S3.new(s3_init_params.
      merge(region: bucket.location_constraint))
    bucket = s3.buckets[@bucket_name]
  end
  @bucket = bucket
end

#open_file(key) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/filer/s3.rb', line 45

def open_file(key)
  o = bucket.objects[key]
  filename = File.basename(key)
  ext = File.extname(key)
  t = Tempfile.new([filename, ext])
  o.read do |ch| t.write(ch) end
  t.close
  # seems like a race condition
  sleep 1
  `open #{t.path}`
end

#put_file(path) ⇒ Object



40
41
42
43
# File 'lib/filer/s3.rb', line 40

def put_file(path)
  o = bucket.objects[s3_key(path)]
  o.write(Pathname.new(path), server_side_encryption: :aes256)
end

#s3Object



16
17
18
# File 'lib/filer/s3.rb', line 16

def s3
  @s3 ||= AWS::S3.new(s3_init_params)
end

#s3_init_paramsObject



11
12
13
14
# File 'lib/filer/s3.rb', line 11

def s3_init_params
  { access_key_id: @key, secret_access_key: @secret,
    server_side_encryption: :aes256 }
end

#s3_key(path) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/filer/s3.rb', line 32

def s3_key(path)
  filename = File.basename(path)
  y = Time.now.strftime("%Y")
  m = Time.now.strftime("%m")
  d = Time.now.strftime("%d")
  "#{y}/#{m}/#{d}/#{filename}"
end