Class: Rack::File

### Home Classes Methods

### In Files

- lib/rack/file.rb

### Parent

Object

### Methods

- ::new
- #_call
- #call
- #each
- #serving

### Files

- KNOWN-ISSUES

### Class/Module Index

Quicksearch

- Rack
- Rack::Auth
- Rack::Auth::AbstractHandler
- Rack::Auth::AbstractRequest
- Rack::Auth::Basic
- Rack::Auth::Basic::Request
- Rack::Auth::Digest
- Rack::Auth::Digest::MD5
- Rack::Auth::Digest::Nonce
- Rack::Auth::Digest::Params
- Rack::Auth::Digest::Request
- Rack::BodyProxy
- Rack::Builder
- Rack::Cascade
- Rack::Chunked
- Rack::Chunked::Body
- Rack::CommonLogger
- Rack::ConditionalGet
- Rack::Config
- Rack::ContentLength
- Rack::ContentType
- Rack::Deflater
- Rack::Deflater::DeflateStream
- Rack::Deflater::GzipStream
- Rack::Directory
- Rack::ETag
- Rack::File
- Rack::ForwardRequest
- Rack::Handler
- Rack::Handler::CGI
- Rack::Handler::EventedMongrel
- Rack::Handler::FastCGI
- Rack::Handler::LSWS
- Rack::Handler::Mongrel
- Rack::Handler::SCGI
- Rack::Handler::SwiftipliedMongrel
- Rack::Handler::Thin
- Rack::Handler::WEBrick
- Rack::Head
- Rack::Lint
- Rack::Lobster
- Rack::Lock
- Rack::Logger
- Rack::MethodOverride
- Rack::Mime
- Rack::MockRequest
- Rack::MockRequest::FatalWarner
- Rack::MockRequest::FatalWarning
- Rack::MockResponse
- Rack::Multipart
- Rack::Multipart::Generator
- Rack::Multipart::MultipartLimitError
- Rack::Multipart::Parser
- Rack::Multipart::UploadedFile
- Rack::NullLogger
- Rack::Recursive
- Rack::Reloader
- Rack::Reloader::Stat
- Rack::Request
- Rack::Response
- Rack::Response::Helpers
- Rack::RewindableInput
- Rack::RewindableInput::Tempfile
- Rack::Runtime
- Rack::Sendfile
- Rack::Server
- Rack::Server::Options
- Rack::Session
- Rack::Session::Abstract
- Rack::Session::Abstract::ID
- Rack::Session::Abstract::SessionHash
- Rack::Session::Cookie
- Rack::Session::Cookie::Base64
- Rack::Session::Cookie::Base64::Marshal
- Rack::Session::Cookie::Identity
- Rack::Session::Cookie::Reverse
- Rack::Session::Memcache
- Rack::Session::Pool
- Rack::ShowExceptions
- Rack::ShowStatus
- Rack::Static
- Rack::URLMap
- Rack::Utils
- Rack::Utils::Context
- Rack::Utils::HeaderHash
- Rack::Utils::KeySpaceConstrainedParams
- Rack::Utils::Multipart
- FCGI
- FCGI::Stream
- Object

No matching classes.

# Rack::File

Rack::File serves files below the `root` directory given, according to the path info of the Rack request. e.g. when Rack::File.new("/etc") is used, you can access 'passwd' file as localhost:9292/passwd

Handlers can detect if bodies are a Rack::File, and use mechanisms like sendfile on the `path`.

### Constants

ALLOWED_VERBS
F
SEPS

### Attributes

cache_control[RW]
path[RW]
root[RW]
to_path[RW]

### Public Class Methods

new(root, headers={}) click to toggle source

    # File lib/rack/file.rb, line 24
    def initialize(root, headers={})
      @root = root
      # Allow a cache_control string for backwards compatibility
      if headers.instance_of? String
        warn            "Rack::File headers parameter replaces cache_control after Rack 1.5."
        @headers = { 'Cache-Control' => headers }
      else
        @headers = headers
      end
    end

### Public Instance Methods

_call(env) click to toggle source

    # File lib/rack/file.rb, line 42
    def _call(env)
      unless ALLOWED_VERBS.include? env["REQUEST_METHOD"]
        return fail(405, "Method Not Allowed")
      end

      @path_info = Utils.unescape(env["PATH_INFO"])
      parts = @path_info.split SEPS

      clean = []

      parts.each do |part|
        next if part.empty? || part == '.'
        part == '..' ? clean.pop : clean << part
      end

      @path = F.join(@root, *clean)

      available = begin
        F.file?(@path) && F.readable?(@path)
      rescue SystemCallError
        false
      end

      if available
        serving(env)
      else
        fail(404, "File not found: #{@path_info}")
      end
    end

call(env) click to toggle source

    # File lib/rack/file.rb, line 36
    def call(env)
      dup._call(env)
    end

each() click to toggle source

    # File lib/rack/file.rb, line 116
    def each
      F.open(@path, "rb") do |file|
        file.seek(@range.begin)
        remaining_len = @range.end-@range.begin+1
        while remaining_len > 0
          part = file.read([8192, remaining_len].min)
          break unless part
          remaining_len -= part.length

          yield part
        end
      end
    end

serving(env) click to toggle source

    # File lib/rack/file.rb, line 72
    def serving(env)
      last_modified = F.mtime(@path).httpdate
      return [304, {}, []] if env['HTTP_IF_MODIFIED_SINCE'] == last_modified
      response = [
        200,
        {
          "Last-Modified"  => last_modified,
          "Content-Type"   => Mime.mime_type(F.extname(@path), 'text/plain')
        },
        env["REQUEST_METHOD"] == "HEAD" ? [] : self
      ]

      # Set custom headers
      @headers.each { |field, content| response[1][field] = content } if @headers

      # NOTE:
      #   We check via File::size? whether this file provides size info
      #   via stat (e.g. /proc files often don't), otherwise we have to
      #   figure it out by reading the whole file into memory.
      size = F.size?(@path) || Utils.bytesize(F.read(@path))

      ranges = Rack::Utils.byte_ranges(env, size)
      if ranges.nil? || ranges.length > 1
        # No ranges, or multiple ranges (which we don't support):
        # TODO: Support multiple byte-ranges
        response[0] = 200
        @range = 0..size-1
      elsif ranges.empty?
        # Unsatisfiable. Return error, and file size:
        response = fail(416, "Byte range unsatisfiable")
        response[1]["Content-Range"] = "bytes */#{size}"
        return response
      else
        # Partial content:
        @range = ranges[0]
        response[0] = 206
        response[1]["Content-Range"] = "bytes #{@range.begin}-#{@range.end}/#{size}"
        size = @range.end - @range.begin + 1
      end

      response[1]["Content-Length"] = size.to_s
      response
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.