Sha256: bebaab9f923c3f9dfc0596d92c322bfb405b8913c697d73410187c724eabbb05

Contents?: true

Size: 868 Bytes

Versions: 9

Compression:

Stored size: 868 Bytes

Contents

module Rasti
  module Web
    class Route

      attr_reader :pattern

      def initialize(pattern, endpoint=nil, &block)
        @pattern = normalize pattern
        @endpoint = endpoint || Endpoint.new(&block)
        @regexp = compile
      end

      def match?(path)
        !@regexp.match(normalize(path)).nil?
      end

      def extract_params(path)
        result = @regexp.match path
        result ? result.names.each_with_object({}) { |v,h| h[v] = result[v] } : {}
      end

      def call(env)
        @endpoint.call env
      end

      private

      def compile
        %r{^#{pattern.gsub(')', '){0,1}').gsub(/:[a-z0-9_-]+/) { |var| "(?<#{var[1..-1]}>[^\/?#]+)" }}$}
      end

      def normalize(path)
        return '/' if path.strip.empty? || path == '/'
        return path[0..-2] if path[-1, 1] == '/'
        path
      end

    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
rasti-web-0.2.3 lib/rasti/web/route.rb
rasti-web-0.2.2 lib/rasti/web/route.rb
rasti-web-0.2.1 lib/rasti/web/route.rb
rasti-web-0.2.0 lib/rasti/web/route.rb
rasti-web-0.1.1 lib/rasti/web/route.rb
rasti-web-0.1.0 lib/rasti/web/route.rb
rasti-web-0.0.7 lib/rasti/web/route.rb
rasti-web-0.0.6 lib/rasti/web/route.rb
rasti-web-0.0.5 lib/rasti/web/route.rb