Sha256: 71faceaa59778ef7b42815eff8d35db02c1a285c911725d4582a22c33641fba3

Contents?: true

Size: 1.24 KB

Versions: 6

Compression:

Stored size: 1.24 KB

Contents

require 'rack'

module Machined
  module Middleware
    # Machined::Middleware::Static serves static files
    # from the given directory. If no static file is
    # found, the request gets passed on to the next
    # middleware or application. It's basically
    # a simplified version of ActionDispatch::Static.
    class Static
      def initialize(app, root = '.', headers = {})
        @app = app
        @root = File.expand_path(root)
        @compiled_root = /^#{Regexp.escape(@root)}/
        @file_server = ::Rack::File.new(@root, headers)
      end

      def call(env)
        case env['REQUEST_METHOD']
        when 'GET', 'HEAD'
          path = env['PATH_INFO'].chomp('/')
          if match = match?(path)
            env['PATH_INFO'] = match
            return @file_server.call(env)
          end
        end

        @app.call(env)
      end

      protected

      def match?(path)
        full_path = path.empty? ? @root : File.join(@root, path)
        matches = Dir[full_path + '{,.html,/index.html}']
        match = matches.detect { |f| File.file?(f) }

        if match
          ::Rack::Utils.escape match.sub(@compiled_root, '')
        else
          nil
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
machined-1.1.0 lib/machined/middleware/static.rb
machined-1.0.3 lib/machined/middleware/static.rb
machined-1.0.2 lib/machined/middleware/static.rb
machined-1.0.1 lib/machined/middleware/static.rb
machined-1.0.0 lib/machined/middleware/static.rb
machined-0.9.3 lib/machined/middleware/static.rb