Class: Ramaze::Route
Overview
Ramaze support simple routing using string, regex and lambda based routers. Route are stored in a dictionary, which supports hash-like access but preserves order, so routes are evaluated in the order they are added.
String routers are the simplest way to route in Ramaze. One path is translated into another:
Ramaze::Route[ '/foo' ] = '/bar'
'/foo' => '/bar'
Regex routers allow matching against paths using regex. Matches within your regex using () are substituted in the new path using printf-like syntax.
Ramaze::Route[ %r!^/(\d+)\.te?xt$! ] = "/text/%d"
'/123.txt' => '/text/123'
'/789.text' => '/text/789'
For more complex routing, lambda routers can be used. Lambda routers are passed in the current path and request object, and must return either a new path string, or nil.
Ramaze::Route[ 'name of route' ] = lambda{ |path, request|
'/bar' if path == '/foo' and request[:bar] == '1'
}
'/foo' => '/foo'
'/foo?bar=1' => '/bar'
Lambda routers can also use this alternative syntax:
Ramaze::Route('name of route') do |path, request|
'/bar' if path == '/foo' and request[:bar] == '1'
end
Direct Known Subclasses
Class Method Summary collapse
-
.[](key) ⇒ Object
Retrieve key from trait.
-
.[]=(key, value) ⇒ Object
Set key to value in trait.
-
.clear ⇒ Object
remove all routes.
-
.resolve(path) ⇒ Object
Resolve path according to routes.
Class Method Details
.[](key) ⇒ Object
Retrieve key from trait
45 46 47 |
# File 'lib/ramaze/route.rb', line 45 def [](key) trait[:routes][key] end |
.[]=(key, value) ⇒ Object
Set key to value in trait
50 51 52 |
# File 'lib/ramaze/route.rb', line 50 def []=(key, value) trait[:routes][key] = value end |
.clear ⇒ Object
remove all routes
55 56 57 |
# File 'lib/ramaze/route.rb', line 55 def clear trait[:routes].clear end |
.resolve(path) ⇒ Object
Resolve path according to routes.
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/ramaze/route.rb', line 60 def resolve(path) trait[:routes].each do |key, val| if key.is_a?(Regexp) if md = path.match(key) return val % md.to_a[1..-1] end elsif val.respond_to?(:call) if new_path = val.call(path, Request.current) return new_path end elsif val.is_a?(String) return val if path == key else Log.error "Invalid route #{key} => #{val}" end end nil end |