Sha256: eb538c1983a9e9227d78dff257b4a443ad2b8f88ed779889605761075bf4e942

Contents?: true

Size: 1.27 KB

Versions: 3

Compression:

Stored size: 1.27 KB

Contents

require 'rack'
require 'font_assets/mime_types'

module FontAssets
  class Middleware

    def initialize(app, origin)
      @app = app
      @origin = origin
      @mime_types = FontAssets::MimeTypes.new(Rack::Mime::MIME_TYPES)
    end

    def access_control_headers
      {
        "Access-Control-Allow-Origin" => @origin,
        "Access-Control-Allow-Methods" => "GET",
        "Access-Control-Allow-Headers" => "x-requested-with",
        "Access-Control-Max-Age" => "3628800"
      }
    end

    def call(env)
      # intercept the "preflight" request
      if env["REQUEST_METHOD"] == "OPTIONS"
        return [200, access_control_headers, []]
      else
        code, headers, body = @app.call(env)
        set_headers! headers, body, env["PATH_INFO"]
        [code, headers, body]
      end
    end


    private


    def extension(path)
      "." + path.split("?").first.split(".").last
    end

    def font_asset?(path)
      @mime_types.font? extension(path)
    end

    def set_headers!(headers, body, path)
      if ext = extension(path) and font_asset?(ext)
        headers.merge!(access_control_headers)
        headers.merge!('Content-Type' => mime_type(ext)) if headers['Content-Type']
      end
    end

    def mime_type(extension)
      @mime_types[extension]
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
font_assets-0.1.3 lib/font_assets/middleware.rb
font_assets-0.1.2 lib/font_assets/middleware.rb
font_assets-0.1.1 lib/font_assets/middleware.rb