Class: Dimension::Middleware

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

Constant Summary collapse

EXCEEDED =
[403, {'Content-Type' => 'text/plain'}, ['Limit Exceeded.']]

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ Middleware

Returns a new instance of Middleware.



10
11
12
13
14
15
16
17
18
# File 'lib/dimension/middleware.rb', line 10

def initialize(app, opts = {})
  @app  = app
  @root = File.expand_path(opts[:root] || Dir.pwd())
  @save = opts[:save]
  
  if opts[:throttle]
    @throttle = Rack::Throttle::Interval.new(self, :min => opts[:throttle])
  end
end

Instance Method Details

#call(env) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/dimension/middleware.rb', line 20

def call(env)
  url      = env['PATH_INFO']
  geometry = url[/-([0-9x:-]+)\.(png|gif|jpe?g)/i, 1]
  
  return @app.call(env) unless geometry

  resized  = File.join(@root, url)
  original = resized.sub("-#{geometry}", '')

  if !File.exist?(resized) and File.exist?(original)
    
    if @throttle
      req = Rack::Request.new(env)
      return EXCEEDED unless @throttle.allowed?(req)
    end
    
    # puts 'Processing image: ' + file
    image = Dimension.open(original)
    image.generate(geometry) do
      image.save_as(resized) if @save
      return image.to_response
    end
  end

  @app.call(env)
rescue ArgumentError => e # Dimension::Error
  # puts "Error processing image: #{e.message}"
  @app.call(env)
end