Sha256: fa2b15b5df89e43d745fcc4d7bb01c359c3d00cbfdd9009a57671dd7bba8fdec

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 KB

Contents

require 'sitehub/getter_setter_methods'
require 'sitehub/constants'
require 'sitehub/nil_route'
require 'rack/request'
require 'rack/response'
require 'rack/utils'
require 'em-http'

class SiteHub
  module Middleware
    class CandidateRouteMappings < Hash
      NIL_ROUTE = NilRoute.new

      include Equality

      extend GetterSetterMethods
      getter_setter :sitehub_cookie_name, RECORDED_ROUTES_COOKIE

      def initialize
        self.default = NIL_ROUTE
      end

      def call(env)
        source_request = Rack::Request.new(env)

        route = mapped_route(path: source_request.path, request: source_request)

        route.call(env)
      end

      def init
        values.each(&:build)
        self
      end

      def add_route(url: nil, mapped_path: nil, route_builder: nil, &block)
        unless route_builder
          route_builder = CandidateRoutes.new(sitehub_cookie_name: sitehub_cookie_name,
                                              mapped_path: mapped_path,
                                              &block).tap do |builder|
            builder.default(url: url) if url
          end
        end

        self[route_builder.mapped_path] = route_builder
      end

      def mapped_route(path:, request:)
        self[mapping(path)].resolve(id: request.cookies[sitehub_cookie_name], env: request.env)
      end

      def mapping(path)
        keys.find do |key|
          case key
          when Regexp
            key.match(path)
          else
            path == key
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sitehub-0.5.0.alpha10 lib/sitehub/middleware/candidate_route_mappings.rb