Sha256: 8116848eecb4202842ea25a5faeca80835688fd73da5b09cfd345ebd3374c69a

Contents?: true

Size: 1.52 KB

Versions: 8

Compression:

Stored size: 1.52 KB

Contents

require "addressable/template"

module Ramaze
  # This is a simple prototype-implementation of how we could do routing
  # supported by URI templates.
  #
  # Please see the spec for example usage as it's not integrated yet in any way.
  #
  # What it does is basically that you can give it any URI template and a final
  # mapping, and it will extract the variables from the URI and merge them into
  # the QUERY_STRING, which is parsed again in Ramaze if you issue
  # Request#params.
  #
  # @example given mapping like:
  #
  #     map('/customer/{customer_id}/order/{order_id}', '/order/show')
  #
  # @example output of request.params at '/order/show'
  #
  #     {'customer_id => '12', 'order_id' => '15'}
  #     
  # I haven't explored the full capabilities of the templates yet, but the
  # specs of Addressable::Template suggest that there is a lot to be
  # discovered.
  class AddressableRoute
    ROUTES = {}

    def self.map(from, to)
      ROUTES[Addressable::Template.new(from)] = to
    end

    def initialize(app)
      @app = app
    end

    def call(env)
      path_info = env['PATH_INFO']

      ROUTES.each do |template, target|
        extracted = template.extract(path_info)
        return dispatch(env, target, extracted) if extracted
      end

      @app.call(env)
    end

    def dispatch(env, target, extracted)
      env['PATH_INFO'] = target
      original = Rack::Utils.parse_query(env['QUERY_STRING'])
      env['QUERY_STRING'] = Rack::Utils.build_query(original.merge(extracted))

      @app.call(env)
    end
  end
end

Version data entries

8 entries across 8 versions & 3 rubygems

Version Path
manveru-ramaze-2009.06.04 lib/ramaze/contrib/addressable_route.rb
manveru-ramaze-2009.06.12 lib/ramaze/contrib/addressable_route.rb
manveru-ramaze-2009.06 lib/ramaze/contrib/addressable_route.rb
rjspotter-ramaze-2009.06.29 lib/ramaze/contrib/addressable_route.rb
rjspotter-ramaze-2009.06.31 lib/ramaze/contrib/addressable_route.rb
ramaze-2009.06 lib/ramaze/contrib/addressable_route.rb
ramaze-2009.06.12 lib/ramaze/contrib/addressable_route.rb
ramaze-2009.06.04 lib/ramaze/contrib/addressable_route.rb