Class: PhotoCook::Resize::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/photo-cook/resize/middleware.rb

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



13
14
15
# File 'lib/photo-cook/resize/middleware.rb', line 13

def initialize(app)
  @app = app
end

Class Attribute Details

.headersObject

Returns the value of attribute headers.



8
9
10
# File 'lib/photo-cook/resize/middleware.rb', line 8

def headers
  @headers
end

Instance Method Details

#call(env) ⇒ Object

Consider we have car.png in /uploads/photos/1/car.png We want to resize it with the following params:

Width:       choose automatically
Height:      exactly 640px
Mode:        fill

Middleware will handle this URI:

/uploads/photos/1/resized/width=auto&height=640&mode=fill/car.png


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/photo-cook/resize/middleware.rb', line 26

def call(env)
  uri = extract_uri(env)

  # Check if URI contains PhotoCook resize indicators
  return default_action(env) unless Assemble.resize_uri?(uri)

  # If resized photo exists but nginx or apache didn't handle this request
  return respond_with_file(env) if requested_file_exists?(uri)

  # At this point we are sure that this request is targeting to resize photo
  PhotoCook.notify('resize:middleware:match', uri)

  # Matched data: width=auto&height=640&mode=fill
  command = Command.extract(uri)

  # Assemble path of the source photo:
  #   => /application/public/uploads/photos/1/car.png
  source_path = Assemble.assemble_source_path_from_resize_uri(root_path, uri)

  # Assemble path of the resized photo:
  #   => /application/public/resized/uploads/photos/1/COMMAND/car.png
  store_path = Assemble.assemble_store_path(root_path, source_path, command.to_s)

  if File.file?(store_path) && File.readable?(store_path)
    symlink_cache_dir(source_path, store_path)
    respond_with_file(env)

  elsif File.file?(source_path) && File.readable?(source_path)
    # Finally resize photo
    # Resized photo will appear in resize directory
    Resize.perform(source_path, store_path, command[:width], command[:height], command[:mode])
    symlink_cache_dir(source_path, store_path)
    respond_with_file(env)

  else
    default_action(env)
  end
end