### Home Classes Methods

### In Files

- lib/merb-core/dispatch/router.rb
- lib/merb-core/dispatch/router/route.rb
- lib/merb-core/dispatch/router/resources.rb
- lib/merb-core/dispatch/router/behavior.rb
- lib/merb-core/dispatch/router/cached_proc.rb

### Parent

Object

### Namespace

- MODULE Merb::Router::Resources
- CLASS Merb::Router::Behavior
- CLASS Merb::Router::CachedProc
- CLASS Merb::Router::GenerationError
- CLASS Merb::Router::NotCompiledError
- CLASS Merb::Router::RouteNotFound

### Methods

- ::extensions
- ::prepare
- ::reset!
- ::resource
- ::route_for
- ::url

### Files

- CHANGELOG
- LICENSE
- README
- TODO

### Class/Module Index

Quicksearch

- Merb
- Merb::AbstractController
- Merb::AcceptType
- Merb::AuthenticationMixin
- Merb::AuthenticationMixin::BasicAuthentication
- Merb::BootLoader
- Merb::BootLoader::AfterAppLoads
- Merb::BootLoader::BackgroundServices
- Merb::BootLoader::BeforeAppLoads
- Merb::BootLoader::BuildFramework
- Merb::BootLoader::ChooseAdapter
- Merb::BootLoader::Cookies
- Merb::BootLoader::Defaults
- Merb::BootLoader::Dependencies
- Merb::BootLoader::DropPidFile
- Merb::BootLoader::LoadClasses
- Merb::BootLoader::Logger
- Merb::BootLoader::MimeTypes
- Merb::BootLoader::MixinSession
- Merb::BootLoader::RackUpApplication
- Merb::BootLoader::ReloadClasses
- Merb::BootLoader::ReloadClasses::TimedExecutor
- Merb::BootLoader::Router
- Merb::BootLoader::SetupSession
- Merb::BootLoader::SetupStubClasses
- Merb::BootLoader::Templates
- Merb::ConditionalGetMixin
- Merb::Config
- Merb::Config::ConfigBlock
- Merb::Const
- Merb::Controller
- Merb::ControllerExceptions
- Merb::ControllerExceptions::Accepted
- Merb::ControllerExceptions::ActionNotFound
- Merb::ControllerExceptions::BadGateway
- Merb::ControllerExceptions::BadRequest
- Merb::ControllerExceptions::Base
- Merb::ControllerExceptions::ClientError
- Merb::ControllerExceptions::Conflict
- Merb::ControllerExceptions::Continue
- Merb::ControllerExceptions::Created
- Merb::ControllerExceptions::ExpectationFailed
- Merb::ControllerExceptions::Forbidden
- Merb::ControllerExceptions::GatewayTimeout
- Merb::ControllerExceptions::Gone
- Merb::ControllerExceptions::HTTPVersionNotSupported
- Merb::ControllerExceptions::Informational
- Merb::ControllerExceptions::InternalServerError
- Merb::ControllerExceptions::LayoutNotFound
- Merb::ControllerExceptions::LengthRequired
- Merb::ControllerExceptions::MethodNotAllowed
- Merb::ControllerExceptions::MovedPermanently
- Merb::ControllerExceptions::MovedTemporarily
- Merb::ControllerExceptions::MultiPartParseError
- Merb::ControllerExceptions::MultipleChoices
- Merb::ControllerExceptions::NoContent
- Merb::ControllerExceptions::NonAuthoritativeInformation
- Merb::ControllerExceptions::NotAcceptable
- Merb::ControllerExceptions::NotFound
- Merb::ControllerExceptions::NotImplemented
- Merb::ControllerExceptions::NotModified
- Merb::ControllerExceptions::OK
- Merb::ControllerExceptions::PartialContent
- Merb::ControllerExceptions::PaymentRequired
- Merb::ControllerExceptions::PreconditionFailed
- Merb::ControllerExceptions::ProxyAuthenticationRequired
- Merb::ControllerExceptions::Redirection
- Merb::ControllerExceptions::RequestEntityTooLarge
- Merb::ControllerExceptions::RequestRangeNotSatisfiable
- Merb::ControllerExceptions::RequestTimeout
- Merb::ControllerExceptions::RequestURITooLarge
- Merb::ControllerExceptions::ResetContent
- Merb::ControllerExceptions::SeeOther
- Merb::ControllerExceptions::ServerError
- Merb::ControllerExceptions::ServiceUnavailable
- Merb::ControllerExceptions::Successful
- Merb::ControllerExceptions::SwitchingProtocols
- Merb::ControllerExceptions::TemplateNotFound
- Merb::ControllerExceptions::TemporaryRedirect
- Merb::ControllerExceptions::Unauthorized
- Merb::ControllerExceptions::UnsupportedMediaType
- Merb::ControllerExceptions::UseProxy
- Merb::ControllerMixin
- Merb::CookieSession
- Merb::CookieSession::CookieOverflow
- Merb::CookieSession::TamperedWithCookie
- Merb::Cookies
- Merb::CookiesMixin
- Merb::CookiesMixin::RequestMixin
- Merb::Counter
- Merb::Dispatcher
- Merb::Dispatcher::DefaultException
- Merb::Dispatcher::DefaultExceptionHelper
- Merb::GlobalHelpers
- Merb::InlineTemplates
- Merb::Logger
- Merb::MemcacheSession
- Merb::MemcacheStore
- Merb::MemorySession
- Merb::MemorySessionStore
- Merb::Parse
- Merb::Plugins
- Merb::Rack
- Merb::Rack::AbstractAdapter
- Merb::Rack::Adapter
- Merb::Rack::Application
- Merb::Rack::ConditionalGet
- Merb::Rack::Console
- Merb::Rack::ContentLength
- Merb::Rack::DeferrableMiddleware
- Merb::Rack::Ebb
- Merb::Rack::EventedMongrel
- Merb::Rack::FastCGI
- Merb::Rack::Handler
- Merb::Rack::Handler::Mongrel
- Merb::Rack::Head
- Merb::Rack::Helpers
- Merb::Rack::Irb
- Merb::Rack::Middleware
- Merb::Rack::Mongrel
- Merb::Rack::PathPrefix
- Merb::Rack::Profiler
- Merb::Rack::Runner
- Merb::Rack::Static
- Merb::Rack::StreamWrapper
- Merb::Rack::SwiftipliedMongrel
- Merb::Rack::Thin
- Merb::Rack::ThinTurbo
- Merb::Rack::Tracer
- Merb::Rack::WEBrick
- Merb::RenderMixin
- Merb::RenderMixin::ClassMethods
- Merb::Request
- Merb::ReservedError
- Merb::Responder
- Merb::ResponderMixin
- Merb::ResponderMixin::ClassMethods
- Merb::ResponderMixin::ContentTypeAlreadySet
- Merb::Router
- Merb::Router::Behavior
- Merb::Router::Behavior::Error
- Merb::Router::Behavior::Proxy
- Merb::Router::CachedProc
- Merb::Router::GenerationError
- Merb::Router::NotCompiledError
- Merb::Router::Resources
- Merb::Router::RouteNotFound
- Merb::Server
- Merb::Session
- Merb::SessionContainer
- Merb::SessionMixin
- Merb::SessionMixin::NoSessionContainer
- Merb::SessionMixin::RequestMixin
- Merb::SessionMixin::RequestMixin::ClassMethods
- Merb::SessionMixin::SessionOverflow
- Merb::SessionStoreContainer
- Merb::System
- Merb::System::PortablePoller
- Merb::Template
- Merb::Template::Erubis
- Merb::Template::Erubis::Mixin
- Merb::Test
- Merb::Test::ControllerHelper
- Merb::Test::Cookie
- Merb::Test::CookieJar
- Merb::Test::ExampleGroup
- Merb::Test::Helpers
- Merb::Test::MakeRequest
- Merb::Test::Matchers
- Merb::Test::MultipartRequestHelper
- Merb::Test::MultipartRequestHelper::FileParam
- Merb::Test::MultipartRequestHelper::Param
- Merb::Test::MultipartRequestHelper::Post
- Merb::Test::RequestHelper
- Merb::Test::RequestHelper::CookieJar
- Merb::Test::RequestHelper::FakeRequest
- Merb::Test::RouteHelper
- Merb::Test::Rspec
- Merb::Test::Rspec::ControllerMatchers
- Merb::Test::Rspec::ControllerMatchers::BeError
- Merb::Test::Rspec::ControllerMatchers::BeRedirect
- Merb::Test::Rspec::ControllerMatchers::Provide
- Merb::Test::Rspec::RouteMatchers
- Merb::Test::Rspec::RouteMatchers::ParameterMatcher
- Merb::Test::Rspec::RouteMatchers::RouteToMatcher
- Merb::Test::ViewHelper
- Merb::Test::WebratHelper
- Merb::Worker
- Erubis
- Erubis::Basic
- Erubis::Basic::Converter
- Erubis::BlockAwareEnhancer
- Erubis::BlockAwareEruby
- Erubis::MEruby
- Spec
- Spec::Matchers
- Spec::Matchers::MatcherDSL
- Spec::Runner
- Spec::Runner::Formatter
- Spec::Runner::Formatter::BaseTextFormatter
- Gem
- Gem::Dependency
- Hpricot
- Hpricot::Elem
- Mongrel
- Mongrel::HttpResponse
- Class
- Exception
- Hash
- Kernel
- MemCache
- Memcached
- Object
- String
- Time

No matching classes.

# Merb::Router

Router stores route definitions and finds the first route that matches the incoming request URL.

Then information from route is used by dispatcher to call action on the controller.

#### Routes compilation.

The most interesting method of Router (and heart of route matching machinery) is match method generated on the fly from routes definitions. It is called routes compilation. Generated match method body contains one if/elsif statement that picks the first matching route definition and sets values to named parameters of the route.

Compilation is synchronized by mutex.

### Attributes

around_match[RW]

A block that will be run around route matching. This block must yield in order for the actual matching to happen.

:api: plugin

named_routes[RW]

A hash containing all the named application routes. The names are absolute (as in, all routes named in a namespace will contain the name of the namespace).

:api: private

resource_routes[RW]

A hash of all the application resource routes. The key of the hash is an array with each element containing the "path" for the resource for example, given the following resource routes:

resources :users do

    resources :comments

end

The show comment route will have a key of ["User", "Comment"]

:api: private

root_behavior[RW]

The starting point for route definition. Any route defined in a Merb::Router.prepare block will defined in context of this behavior.

#### Examples

Merb::Router.root_behavior = Merb::Router.root_bavior.match("/hello")

In the previous example, all routes will have the path prefix /hello. It is important to note that this attribute must be set before any routes are defined in order for the behavior to be applied to the routes.

:api: plugin

routes[RW]

An array containing all the application routes in order of priority.

:api: private

### Public Class Methods

extensions(&block) click to toggle source

Add functionality to the router. This can be in the form of including a new module or directly defining new methods.

#### Parameters

&block<Block> | A block of code used to extend the route builder with. This can be including a module or directly defining some new methods that should be available to building routes.

#### Returns

nil

#### Example

    Merb::Router.extensions do
      def domain(name, domain, options={}, &block)
        match(:domain => domain).namespace(name, :path => nil, &block)
      end
    end

In this case, a method 'domain' will be available to the route builder which will create namespaces around domains instead of path prefixes.

This can then be used as follows.

    Merb::Router.prepare do
      domain(:admin, "my-admin.com") do
        # ... routes come here ...
      end
    end

:api: public

    # File lib/merb-core/dispatch/router.rb, line 310
    def extensions(&block)
      Router::Behavior.class_eval(&block)
    end

prepare(first = [], last = [], &block) click to toggle source

Creates a route building context and evaluates the block in it. A copy of `root_behavior` (and instance of Behavior) is copied as the context.

#### Parameters

first<Array> | An array containing routes that should be prepended to the routes defined in the block.
last<Array> | An array containing routes that should be appended to the routes defined in the block.

#### Returns

Merb::Router | Returns self to allow chaining of methods.

:api: public

    # File lib/merb-core/dispatch/router.rb, line 103
    def prepare(first = [], last = [], &block)
      @routes = []
      root_behavior._with_proxy(&block)
      @routes = first + @routes + last
      compile
      self
    end

reset!() click to toggle source

Clears the routing table. Route generation and request matching won't work anymore until a new routing table is built.

:api: private

    # File lib/merb-core/dispatch/router.rb, line 115
    def reset!
      class << self
        alias_method :match, :match_before_compilation
      end
      self.routes, self.named_routes, self.resource_routes = [], {}, {}
    end

resource(*args) click to toggle source

Generates a URL from the resource(s)

#### Parameters

resources<Symbol,Object> | The identifiers for the resource route to generate. These can either be symbols or objects. Symbols denote resource collection routes and objects denote the members.
params<Hash> | Any extra parameters needed to generate the route.

#### Returns

String | The generated URL

:api: plugin

    # File lib/merb-core/dispatch/router.rb, line 255
    def resource(*args)
      defaults = args.pop
      options  = extract_options_from_args!(args) || {}
      key      = []
      params   = []

      args.each do |arg|
        if arg.is_a?(Symbol) || arg.is_a?(String)
          key << arg.to_s
        else
          key << arg.class.to_s
          params << arg
        end
      end

      unless route = Merb::Router.resource_routes[key]
        raise Merb::Router::GenerationError, "Resource route not found: #{args.inspect}"
      end

      params << options

      route.generate(params, defaults, true)
    end

route_for(request) click to toggle source

Finds route matching URI of the request and returns a tuple of [route index, route params]. This method is called by the dispatcher and isn't as useful in applications.

#### Parameters

request<Merb::Request> | request to match.

#### Returns

Array[Integer, Hash] | Two-tuple: route index and route parameters. Route parameters are :controller, :action and all the named segments of the route.

:api: private

    # File lib/merb-core/dispatch/router.rb, line 135
    def route_for(request)
      index, params = if @around_match
        send(@around_match, request) { match(request) }
      else
        match(request)
      end
      route = routes[index] if index
      if !route
        raise ControllerExceptions::NotFound,
          "No routes match the request: #{request.uri}"
      end
      [route, params]
    end

url(name, *args) click to toggle source

There are three possible ways to use this method. First, if you have a named route, you can specify the route as the first parameter as a symbol and any paramters in a hash. Second, you can generate the default route by just passing the params hash, just passing the params hash. Finally, you can use the anonymous parameters. This allows you to specify the parameters to a named route in the order they appear in the router.

#### Parameters(Named Route)

name<Symbol> | The name of the route.
args<Hash> | Parameters for the route generation.

#### Parameters(Default Route)

args<Hash> | Parameters for the route generation. This route will use the default route.

#### Parameters(Anonymous Parameters)

name<Symbol> | The name of the route.
args<Array> | An array of anonymous parameters to generate the route with. These parameters are assigned to the route parameters in the order that they are passed.

#### Returns

String | The generated URL.

#### Examples

Named Route

Merb::Router.prepare do

    match("/articles/:title").to(:controller => :articles, :action => :show).name("articles")

end

url(:articles, :title => "new_article")

Default Route

Merb::Router.prepare do

    default_routes

end

url(:controller => "articles", :action => "new")

Anonymous Paramters

Merb::Router.prepare do

    match("/articles/:year/:month/:title").to(:controller => :articles, :action => :show).name("articles")

end

url(:articles, 2008, 10, "test_article")

:api: plugin

    # File lib/merb-core/dispatch/router.rb, line 221
    def url(name, *args)
      if name.is_a?(Route)
        route = name
      else
        unless name.is_a?(Symbol)
          args.unshift(name)
          name = :default
        end

        unless route = Merb::Router.named_routes[name]
          raise Merb::Router::GenerationError, "Named route not found: #{name}"
        end
      end

      defaults = args.pop

      route.generate(args, defaults)
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.