Class: Rack::S3

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/s3.rb,
lib/rack/s3/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ S3

Returns a new instance of S3.



7
8
9
10
11
12
13
14
15
# File 'lib/rack/s3.rb', line 7

def initialize(app, options={})
  @app    = app
  @prefix = options[:prefix]
  @bucket = options[:bucket]

  AWS::S3::Base.establish_connection!(
    :access_key_id     => options[:access_key_id],
    :secret_access_key => options[:secret_access_key])
end

Instance Method Details

#_call(env) ⇒ Object



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

def _call(env)
  @env = env

  if can_serve?
    [ 200, headers, object.value ]
  else
    @app.call env
  end

rescue AWS::S3::NoSuchKey
  not_found
end

#call(env) ⇒ Object



17
18
19
# File 'lib/rack/s3.rb', line 17

def call(env)
  dup._call env
end

#can_serve?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/rack/s3.rb', line 45

def can_serve?
  path_info.index(@prefix) == 0
end

#headersObject



34
35
36
37
38
39
40
41
42
43
# File 'lib/rack/s3.rb', line 34

def headers
  about = object.about

  { 'Content-Type'   => about['content-type'],
    'Content-Length' => about['content-length'],
    'Etag'           => about['etag'],
    'Last-Modified'  => about['last-modified'],
    'Cache-Control'  => 'public; max-age=2592000'  # cache image for a month
  }
end

#not_foundObject



61
62
63
64
65
66
67
68
# File 'lib/rack/s3.rb', line 61

def not_found
  body = "File not found: #{ path_info }\n"

  [ 404,
    { 'Content-Type'   => "text/plain",
      'Content-Length' => body.size.to_s },
    [ body ]]
end

#objectObject



57
58
59
# File 'lib/rack/s3.rb', line 57

def object
  @object ||= AWS::S3::S3Object.find(path, @bucket)
end

#pathObject



53
54
55
# File 'lib/rack/s3.rb', line 53

def path
  path_info.split('/').last
end

#path_infoObject



49
50
51
# File 'lib/rack/s3.rb', line 49

def path_info
  @env['PATH_INFO']
end