Sha256: 3d8bbdec32ea2e572e375dc341f389f786aafe202b89c0a924e1ba2c75021ace

Contents?: true

Size: 1.48 KB

Versions: 5

Compression:

Stored size: 1.48 KB

Contents

require "rack/utils"
require "uri"


module Lanyon

  # Router class for Lanyon applications.
  class Router

    attr_reader :root

    # Creates a Router for the given root directory.
    def initialize(root)
      @root = File.expand_path(root)
    end

    # Returns the full file system path of the file corresponding to
    # the given URL +path+, or
    #
    # - +:not_found+ if no corresponding file exists,
    # - +:must_redirect+ if the request must be redirected to <tt>path/</tt>.
    #
    def endpoint(path)
      normalized = normalize_path_info(path)

      fullpath = File.join(@root, normalized)
      endpoint = if FileTest.file?(fullpath)
                   fullpath
                 elsif needs_redirect_to_dir?(fullpath)
                   :must_redirect
                 else
                   :not_found
                 end

      endpoint
    end

    # Returns the body of the custom 404 page or +nil+ if none exists.
    def custom_404_body
      filename = File.join(root, "404.html")

      File.exist?(filename) ? File.binread(filename) : nil
    end

    private

    def needs_redirect_to_dir?(fullpath)  # :nodoc:
      !fullpath.end_with?("/") && FileTest.file?(fullpath + "/index.html")
    end

    def unescape_path(path)  # :nodoc:
      URI::Parser.new.unescape(path)
    end

    def normalize_path_info(path_info)  # :nodoc:
      path = unescape_path(path_info)

      path << "index.html"  if path.end_with?("/")

      Rack::Utils.clean_path_info(path)
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
lanyon-0.3.3 lib/lanyon/router.rb
lanyon-0.3.2 lib/lanyon/router.rb
lanyon-0.3.1 lib/lanyon/router.rb
lanyon-0.3.0 lib/lanyon/router.rb
lanyon-0.2.3 lib/lanyon/router.rb