Sha256: 759f3127b8a84299ee3a59c05815a2e08d3b858a7e02dc9703fd8bb8e6a4719d

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

module NYNY
  class Router
    NullHandler = Class.new

    attr_reader :fallback, :routes, :before_hooks, :after_hooks
    def initialize options
      @fallback     = options[:fallback]
      @routes       = options[:routes]
      @before_hooks = options[:before_hooks]
      @after_hooks  = options[:after_hooks]
    end

    def find_handler request
      routes.fetch(request.request_method.downcase.to_sym, []).each do |sig, h|
        params = sig.match request.path
        return [h, params] if params
      end

      [NullHandler, {}]
    end

    def call env
      req = Request.new(env)
      handler, params = find_handler req

      if handler != NullHandler
        process req, handler, params
      else
        fallback.call env
      end
    end

    def process request, handler, url_params
      request.params.merge! url_params
      request.params.default_proc = proc {|h,k| h[k.to_s] || h[k.to_sym]}

      scope = RequestScope.new(request)
      before_hooks.each {|h| scope.instance_eval &h }
      response = scope.apply_to &handler
      after_hooks.each {|h| scope.instance_eval &h }
      response
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
nyny-1.0.0 lib/nyny/router.rb