Class: Rack::Static

### Home Classes Methods

### In Files

- lib/rack/static.rb

### Parent

Object

### Methods

- ::new
- #apply_header_rules
- #apply_rule
- #call
- #can_serve
- #overwrite_file_path
- #route_file
- #set_headers

### 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::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::JSON
- 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
- Rack::Utils::OkJson
- Rack::Utils::OkJson::Error
- Rack::Utils::OkJson::Utf8Error
- FCGI
- FCGI::Stream
- Object

No matching classes.

# Rack::Static

The Rack::Static middleware intercepts requests for static files (javascript files, images, stylesheets, etc) based on the url prefixes or route mappings passed in the options, and serves them using a Rack::File object. This allows a Rack stack to serve both static and dynamic content.

Examples:

Serve all requests beginning with /media from the "media" folder located in the current directory (ie media/*):

    use Rack::Static, :urls => ["/media"]

Serve all requests beginning with /css or /images from the folder "public" in the current directory (ie public/css/* and public/images/*):

    use Rack::Static, :urls => ["/css", "/images"], :root => "public"

Serve all requests to / with "index.html" from the folder "public" in the current directory (ie public/index.html):

    use Rack::Static, :urls => {"/" => 'index.html'}, :root => 'public'

Serve all requests normally from the folder "public" in the current directory but uses index.html as default route for "/"

    use Rack::Static, :urls => [""], :root => 'public', :index =>
    'index.html'

Set custom HTTP Headers for based on rules:

       use Rack::Static, :root => 'public',
           :header_rules => [
             [rule, {header_field => content, header_field => content}],
             [rule, {header_field => content}]
           ]

    Rules for selecting files:

    1) All files
       Provide the :all symbol
       :all => Matches every file

    2) Folders
       Provide the folder path as a string
       '/folder' or '/folder/subfolder' => Matches files in a certain folder

    3) File Extensions
       Provide the file extensions as an array
       ['css', 'js'] or %w(css js) => Matches files ending in .css or .js

    4) Regular Expressions / Regexp
       Provide a regular expression
       %r{\.(?:css|js)\z} => Matches files ending in .css or .js
       /\.(?:eot|ttf|otf|woff|svg)\z/ => Matches files ending in
         the most common web font formats (.eot, .ttf, .otf, .woff, .svg)
         Note: This Regexp is available as a shortcut, using the :fonts rule

    5) Font Shortcut
       Provide the :fonts symbol
       :fonts => Uses the Regexp rule stated right above to match all common web font endings

    Rule Ordering:
      Rules are applied in the order that they are provided.
      List rather general rules above special ones.

    Complete example use case including HTTP header rules:

       use Rack::Static, :root => 'public',
           :header_rules => [
             # Cache all static files in public caches (e.g. Rack::Cache)
             #  as well as in the browser
             [:all, {'Cache-Control' => 'public, max-age=31536000'}],

             # Provide web fonts with cross-origin access-control-headers
             #  Firefox requires this when serving assets using a Content Delivery Network
             [:fonts, {'Access-Control-Allow-Origin' => '*'}]
           ]

### Public Class Methods

new(app, options={}) click to toggle source

    # File lib/rack/static.rb, line 83
    def initialize(app, options={})
      @app = app
      @urls = options[:urls] || ["/favicon.ico"]
      @index = options[:index]
      root = options[:root] || Dir.pwd

      # HTTP Headers
      @header_rules = options[:header_rules] || []
      # Allow for legacy :cache_control option while prioritizing global header_rules setting
      @header_rules.insert(0, [:all, {'Cache-Control' => options[:cache_control]}]) if options[:cache_control]
      @headers = {}

      @file_server = Rack::File.new(root, @headers)
    end

### Public Instance Methods

apply_header_rules() click to toggle source

Convert HTTP header rules to HTTP headers

    # File lib/rack/static.rb, line 124
    def apply_header_rules
      @header_rules.each do |rule, headers|
        apply_rule(rule, headers)
      end
    end

apply_rule(rule, headers) click to toggle source

    # File lib/rack/static.rb, line 130
    def apply_rule(rule, headers)
      case rule
      when :all    # All files
        set_headers(headers)
      when :fonts  # Fonts Shortcut
        set_headers(headers) if @path.match(/\.(?:ttf|otf|eot|woff|svg)\z/)
      when String  # Folder
        path = ::Rack::Utils.unescape(@path)
        set_headers(headers) if (path.start_with?(rule) || path.start_with?('/' + rule))
      when Array   # Extension/Extensions
        extensions = rule.join('|')
        set_headers(headers) if @path.match(/\.(#{extensions})\z/)
      when Regexp  # Flexible Regexp
        set_headers(headers) if @path.match(rule)
      else
      end
    end

call(env) click to toggle source

    # File lib/rack/static.rb, line 110
    def call(env)
      path = env["PATH_INFO"]

      if can_serve(path)
        env["PATH_INFO"] = (path =~ /\/$/ ? path + @index : @urls[path]) if overwrite_file_path(path)
        @path = env["PATH_INFO"]
        apply_header_rules
        @file_server.call(env)
      else
        @app.call(env)
      end
    end

can_serve(path) click to toggle source

    # File lib/rack/static.rb, line 106
    def can_serve(path)
      route_file(path) || overwrite_file_path(path)
    end

overwrite_file_path(path) click to toggle source

    # File lib/rack/static.rb, line 98
    def overwrite_file_path(path)
      @urls.kind_of?(Hash) && @urls.key?(path) || @index && path =~ /\/$/
    end

route_file(path) click to toggle source

    # File lib/rack/static.rb, line 102
    def route_file(path)
      @urls.kind_of?(Array) && @urls.any? { |url| path.index(url) == 0 }
    end

set_headers(headers) click to toggle source

    # File lib/rack/static.rb, line 148
    def set_headers(headers)
      headers.each { |field, content| @headers[field] = content }
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.