Sha256: a784df8afde023a612150e50a5000f2cb761ce93ac2a014e39364e8f1145c043

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 KB

Contents

require "rack/utils"


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:
      Rack::Utils.unescape_path(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

1 entries across 1 versions & 1 rubygems

Version Path
lanyon-0.3.4 lib/lanyon/router.rb