Class: CloudSeed::Middleware

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

Constant Summary collapse

CDN_ASSETS =
['text/css', 'application/javascript', 'text/javascript', 'image/', 'application/pdf', 'audio/', 'video/']
COMPRESSABLE =
["javascript", "json", "atom+xml", "xml", "pdf"].map do |f|
  "application/#{f}"
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



9
10
11
# File 'lib/cloudseed.rb', line 9

def initialize(app)
  self.app = app
end

Instance Attribute Details

#appObject

Returns the value of attribute app.



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

def app
  @app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/cloudseed.rb', line 13

def call(env)
  munge_version(env)

  status, headers, body = app.call(env)

  mime = headers['Content-Type']
  
  if status == 200 && is_compressable?(mime)
    headers['Vary'] = 'Accept-Encoding'
  end

  if is_cloudfront_request?(env) && !headers.has_key?('Expires')
    headers['Expires'] = (Time.now + (365 * 24 * 60 * 60)).utc.rfc2822
  end

  if !is_cloudfront_request?(env) || status == 404 || is_cdn_asset?(mime)
    [status, headers, body]
  else
    [404, {}, ['Not found']]
  end
end

#extract_version(path) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/cloudseed.rb', line 64

def extract_version(path)
  if path =~ /(.+)\.v(\w+)(\.\w+)?$/
    [$1 + $3, $2]
  else
    nil
  end
end

#is_cdn_asset?(mime) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
# File 'lib/cloudseed.rb', line 39

def is_cdn_asset?(mime)
  return true unless mime
  CDN_ASSETS.any?{|c| mime.start_with?(c) }
end

#is_cloudfront_request?(env) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/cloudseed.rb', line 35

def is_cloudfront_request?(env)
  env['HTTP_USER_AGENT'] == 'Amazon CloudFront'
end

#is_compressable?(mime) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
# File 'lib/cloudseed.rb', line 44

def is_compressable?(mime)
  return false unless mime
  return mime.start_with?('text/') ||
    COMPRESSABLE.any?{|c| mime.start_with?(c) }
end

#munge_version(env) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/cloudseed.rb', line 50

def munge_version(env)
  if (v = extract_version(env['PATH_INFO']))
    env['PATH_INFO'] = v.first
    
    qs = env['QUERY_STRING']
    if qs.nil? || qs.strip == ''
      qs = v[1]
    else
      qs = "&#{v[1]}"
    end
    env['QUERY_STRING'] = qs
  end
end