class CarrierWave::PostgresqlTable::RackApp

Constants

READ_CHUNK_SIZE

Public Instance Methods

call(env) click to toggle source
# File lib/carrierwave/postgresql_table/rack_app.rb, line 8
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))
      response_body << chunk
    end
  end

  [200, headers, body]
end