Sha256: 06eaa3e574431e924a9c06d95b620ae389b90d8c34a24ab56ec40f490c4e9ddd

Contents?: true

Size: 997 Bytes

Versions: 13

Compression:

Stored size: 997 Bytes

Contents

# encoding: utf-8

require 'liquid/from_file'

class Router
  include FromFile

  attr_accessor :routes

  def initialize(request_handler)
    @request_handler = request_handler
    @routes = []

    @cache = Hash.new do |hash, path|
      hash[path] = nil
      @routes.each do |regex, block, args|
        match = path.match(regex)
        hash[path] = block.curry[match] if match
      end
      hash[path]
    end
  end

  def add(regexp, args, &block)
    @routes << [regexp, block, args]
  end

  # route %r(/foo/(.+)/(\w+)/(\d+)), AnyParser, :matches, :in, :order
  def route(regexp, parser, *args, &block)
    block = lambda do |match, env|
      params = args.each_with_index.inject({}) do |hash, (name, index)|
        hash[name] = match[index+1]
        hash
      end

      return @request_handler.handle(parser, env, params)
    end

    add(regexp, args, &block)
  end

  def handle(path, request)
    @cache[path].call(request) if @cache[path]
    return !! @cache[path]
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
liquid-ext-2.0.3 lib/liquid/router.rb
liquid-ext-2.0.2 lib/liquid/router.rb
liquid-ext-2.0.1 lib/liquid/router.rb
liquid-ext-2.0.0 lib/liquid/router.rb
liquid-ext-1.2.6 lib/liquid/router.rb
liquid-ext-1.2.2 lib/liquid/router.rb
liquid-ext-1.2.1 lib/liquid/router.rb
liquid-ext-1.2.0 lib/liquid/router.rb
liquid-ext-1.1.1 lib/liquid/router.rb
liquid-ext-1.1.0 lib/liquid/router.rb
liquid-ext-1.0.2 lib/liquid/router.rb
liquid-ext-1.0.1 lib/liquid/router.rb
liquid-ext-1.0.0 lib/liquid/router.rb