Sha256: 1dc45970788cb604519e94ea86f2697e71a81f683ff1f883ce46ad3af34f6a6e

Contents?: true

Size: 877 Bytes

Versions: 4

Compression:

Stored size: 877 Bytes

Contents

module Rasti
  module Web
    class Route

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

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

      def extract_params(path)
        result = regexp.match path
        result ? Hash[params.zip(result.captures)] : {}
      end

      private 

      def compile
        @params = []
        regexp = pattern.gsub(/(:\w+)/) do |match| 
          @params << match[1..-1]
          "([^/?#]+)"
        end
        @regexp = %r{^#{regexp}$}
      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

4 entries across 4 versions & 1 rubygems

Version Path
rasti-web-0.0.4 lib/rasti/web/route.rb
rasti-web-0.0.3 lib/rasti/web/route.rb
rasti-web-0.0.2 lib/rasti/web/route.rb
rasti-web-0.0.1 lib/rasti/web/route.rb