Class: Ale::Bucket

Inherits:
Object
  • Object
show all
Defined in:
lib/ale/bucket.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Bucket

Returns a new instance of Bucket.



16
17
18
# File 'lib/ale/bucket.rb', line 16

def initialize(name)
  @name = name
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/ale/bucket.rb', line 8

def name
  @name
end

Class Method Details

.create(name) ⇒ Object



11
12
13
# File 'lib/ale/bucket.rb', line 11

def create(name)
  self.new(name).tap {|bucket| bucket.create }
end

Instance Method Details

#createObject

Creates the bucket on S3. It does not throw an error if the bucket already exsists.



23
24
25
26
27
# File 'lib/ale/bucket.rb', line 23

def create
  request = Net::HTTP::Put.new(uri.request_uri)
  request.add_field('x-amz-acl', 'private')
  puts send(uri, request)
end

#enable_websiteObject

Allows the bucket to be used to host websites.



31
32
33
34
35
36
# File 'lib/ale/bucket.rb', line 31

def enable_website
  uri = uri(query: 'website')
  request = Net::HTTP::Put.new(uri.request_uri)
  request.body = File.read(File.expand_path('../../templates/website_configuration.xml', __FILE__))
  puts send(uri, request)
end

#exists?Boolean

Returns true of the bucket exsists on S3.

Returns:

  • (Boolean)


40
41
42
43
44
45
# File 'lib/ale/bucket.rb', line 40

def exists?
  request = Net::HTTP::Head.new(uri.request_uri)
  send(uri, request) do |response|
    return response.class == Net::HTTPOK
  end
end

#objectsObject

Returns an array of all of the objects in the bucket.



49
50
51
52
53
54
55
56
57
58
# File 'lib/ale/bucket.rb', line 49

def objects
  uri = uri(prefix: 'prefix=/')
  request = Net::HTTP::Get.new(uri.request_uri)
  send(uri, request) do |response|
    list = Crack::XML.parse(response.body)
    # Make sure we're returning an Array.
    return [] if list['ListBucketResult'].nil?
    return [list['ListBucketResult']['Contents']].flatten.compact
  end
end

#remove(key) ⇒ Object

Removes an object form the bucket.



62
63
64
65
66
# File 'lib/ale/bucket.rb', line 62

def remove(key)
  uri = uri(key)
  request = Net::HTTP::Delete.new(uri.request_uri)
  send(uri, request)
end

#upload(file, key, permissions = 'private') ⇒ Object

Uploads a file to the specified key on S3.



70
71
72
73
74
75
76
77
78
79
# File 'lib/ale/bucket.rb', line 70

def upload(file, key, permissions = 'private')
  uri = uri(key)
  file = File.open(file, 'rb')
  request = Net::HTTP::Put.new(uri.request_uri)
  request.add_field('Content-Length', file.size)
  request.add_field('Content-Type', ContentType.for(file.path))
  request.add_field('x-amz-acl', permissions)
  request.body_stream = file
  send(uri, request)
end