Class: CarrierWave::PostgresqlTable::RackApp

Inherits:
Object
  • Object
show all
Defined in:
lib/carrierwave/postgresql_table/rack_app.rb

Constant Summary collapse

READ_CHUNK_SIZE =
16384

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/carrierwave/postgresql_table/rack_app.rb', line 6

def call(env)
  request = Rack::Request.new(env)

  strip_prefix = "/"
  if(defined?(Rails) && Rails.application && Rails.application.config.relative_url_root)
    strip_prefix = File.join(Rails.application.config.relative_url_root, "/")
  end
  path = request.path.sub(/^#{Regexp.escape(strip_prefix)}/, "")
  file = CarrierWave::Storage::PostgresqlTable::File.new(path)

  unless(file.exists?)
    return [404, { "Content-Type" => "text/plain" }, ["Not Found"]]
  end

  headers = {
    "Last-Modified" => file.last_modified.httpdate,
    "Content-Type" => file.content_type,
    "Content-Disposition" => "inline",
  }

  if(request.params["download"] == "true")
    headers["Content-Disposition"] = "attachment; filename=#{file.filename}"
  end

  body = Enumerator.new do |response_body|
    while(chunk = file.read(READ_CHUNK_SIZE)) do
      response_body << chunk
    end
  end

  [200, headers, body]
end