Class: HttpRouter
- Inherits:
-
Object
- Object
- HttpRouter
- Defined in:
- lib/http_router/version.rb,
lib/http_router.rb,
lib/http_router/node.rb,
lib/http_router/util.rb,
lib/http_router/route.rb,
lib/http_router/request.rb,
lib/http_router/response.rb,
lib/http_router/generator.rb,
lib/http_router/node/glob.rb,
lib/http_router/node/host.rb,
lib/http_router/node/path.rb,
lib/http_router/node/root.rb,
lib/http_router/node/regex.rb,
lib/http_router/node/lookup.rb,
lib/http_router/node/scheme.rb,
lib/http_router/route_helper.rb,
lib/http_router/node/variable.rb,
lib/http_router/node/free_regex.rb,
lib/http_router/node/glob_regex.rb,
lib/http_router/node/user_agent.rb,
lib/http_router/generation_helper.rb,
lib/http_router/node/request_method.rb,
lib/http_router/node/spanning_regex.rb,
lib/http_router/regex_route_generation.rb,
lib/http_router/node/abstract_request_node.rb
Overview
:nodoc
Defined Under Namespace
Modules: GenerationHelper, RegexRouteGeneration, RouteHelper, Util Classes: Generator, Node, RecognizeResponse, Request, Response, Route
Constant Summary collapse
- InvalidRouteException =
Raised when a url is not able to be generated for the given parameters
Class.new(RuntimeError)
- MissingParameterException =
Raised when a Route is not able to be generated due to a missing parameter.
Class.new(RuntimeError)
- InvalidRequestValueError =
Raised an invalid request value is used
Class.new(RuntimeError)
- TooManyParametersException =
Raised when there are extra parameters passed in to #url
Class.new(RuntimeError)
- LeftOverOptions =
Raised when there are left over options
Class.new(RuntimeError)
- AmbiguousVariableException =
Raised when there are duplicate param names specified in a Path
Class.new(RuntimeError)
- VERSION =
'0.11.2'
Instance Attribute Summary collapse
-
#default_app ⇒ Object
Returns the value of attribute default_app.
-
#default_host ⇒ Object
Returns the value of attribute default_host.
-
#default_port ⇒ Object
Returns the value of attribute default_port.
-
#default_scheme ⇒ Object
Returns the value of attribute default_scheme.
-
#named_routes ⇒ Object
readonly
Returns the value of attribute named_routes.
-
#nodes ⇒ Object
readonly
Returns the value of attribute nodes.
-
#root ⇒ Object
readonly
Returns the value of attribute root.
- #route_class ⇒ Object
-
#routes ⇒ Object
readonly
Returns the value of attribute routes.
-
#url_mount ⇒ Object
Returns the value of attribute url_mount.
Instance Method Summary collapse
-
#add(*args, &app) ⇒ Object
Adds a path to be recognized.
- #add_route(route) ⇒ Object
-
#call(env, &callback) ⇒ Object
(also: #compiling_call)
Rack compatible #call.
-
#clone(klass = self.class) ⇒ Object
Creates a deep-copy of the router.
-
#default(app) ⇒ Object
Assigns the default application.
-
#extend_route(&blk) ⇒ Object
Extends the route class with custom features.
-
#get(path, opts = {}, &app) ⇒ Object
Adds a path that only responds to the request method
GET
. -
#ignore_trailing_slash? ⇒ Boolean
Ignore trailing slash feature enabled? See #initialize for details.
-
#initialize(*args, &blk) ⇒ HttpRouter
constructor
Creates a new HttpRouter.
- #inspect ⇒ Object
- #no_response(request, env) ⇒ Object
-
#pass_on_response(response) ⇒ Object
This method defines what sort of responses are considered “passes”, and thus, route processing will continue.
- #path(route, *args) ⇒ Object (also: #compiling_path)
-
#process_destination_path(path, env) ⇒ Object
This method is invoked when a Path object gets called with an env.
- #raw_call(env, &blk) ⇒ Object
- #raw_path(route, *args) ⇒ Object
- #raw_url(route, *args) ⇒ Object
- #raw_url_ns(route, *args) ⇒ Object
-
#recognize(env, &callback) ⇒ Object
Performs recoginition without actually calling the application and returns an array of all matching routes or nil if no match was found.
-
#redirect_trailing_slash? ⇒ Boolean
Redirect trailing slash feature enabled? See #initialize for details.
-
#reset! ⇒ Object
Resets the router to a clean state.
- #rewrite_partial_path_info(env, request) ⇒ Object
- #rewrite_path_info(env, request) ⇒ Object
- #to_s ⇒ Object
- #uncompile ⇒ Object
-
#url(route, *args) ⇒ Object
(also: #compiling_url)
Generate a URL for a specified route.
- #url_ns(route, *args) ⇒ Object (also: #compiling_url_ns)
Constructor Details
#initialize(*args, &blk) ⇒ HttpRouter
Creates a new HttpRouter. Can be called with either HttpRouter.new(proc{|env| ... }, { .. options .. })
or with the first argument omitted. If there is a proc first, then it’s used as the default app in the case of a non-match. Supported options are
-
:default_app – Default application used if there is a non-match on #call. Defaults to 404 generator.
-
:ignore_trailing_slash – Ignore a trailing / when attempting to match. Defaults to
true
. -
:redirect_trailing_slash – On trailing /, redirect to the same path without the /. Defaults to
false
.
43 44 45 46 47 48 49 50 51 52 |
# File 'lib/http_router.rb', line 43 def initialize(*args, &blk) default_app, = args.first.is_a?(Hash) ? [nil, args.first] : [args.first, args[1]] @options = @default_app = default_app || && [:default_app] || proc{|env| ::Rack::Response.new("Not Found", 404, {'X-Cascade' => 'pass'}).finish } @ignore_trailing_slash = && .key?(:ignore_trailing_slash) ? [:ignore_trailing_slash] : true @redirect_trailing_slash = && .key?(:redirect_trailing_slash) ? [:redirect_trailing_slash] : false @route_class = Route reset! instance_eval(&blk) if blk end |
Instance Attribute Details
#default_app ⇒ Object
Returns the value of attribute default_app.
34 35 36 |
# File 'lib/http_router.rb', line 34 def default_app @default_app end |
#default_host ⇒ Object
Returns the value of attribute default_host.
34 35 36 |
# File 'lib/http_router.rb', line 34 def default_host @default_host end |
#default_port ⇒ Object
Returns the value of attribute default_port.
34 35 36 |
# File 'lib/http_router.rb', line 34 def default_port @default_port end |
#default_scheme ⇒ Object
Returns the value of attribute default_scheme.
34 35 36 |
# File 'lib/http_router.rb', line 34 def default_scheme @default_scheme end |
#named_routes ⇒ Object (readonly)
Returns the value of attribute named_routes.
32 33 34 |
# File 'lib/http_router.rb', line 32 def named_routes @named_routes end |
#nodes ⇒ Object (readonly)
Returns the value of attribute nodes.
32 33 34 |
# File 'lib/http_router.rb', line 32 def nodes @nodes end |
#root ⇒ Object (readonly)
Returns the value of attribute root.
32 33 34 |
# File 'lib/http_router.rb', line 32 def root @root end |
#route_class ⇒ Object
101 102 103 104 105 106 107 |
# File 'lib/http_router.rb', line 101 def route_class @extended_route_class ||= begin @route_class.send(:include, RouteHelper) @route_class.send(:include, GenerationHelper) @route_class end end |
#routes ⇒ Object (readonly)
Returns the value of attribute routes.
32 33 34 |
# File 'lib/http_router.rb', line 32 def routes @routes end |
#url_mount ⇒ Object
Returns the value of attribute url_mount.
34 35 36 |
# File 'lib/http_router.rb', line 34 def url_mount @url_mount end |
Instance Method Details
#add(*args, &app) ⇒ Object
Adds a path to be recognized.
To assign a part of the path to a specific variable, use :variable_name within the route. For example, add('/path/:id')
would match /path/test
, with the variable :id
having the value "test"
.
You can receive mulitple parts into a single variable by using the glob syntax. For example, add('/path/*id')
would match /path/123/456/789
, with the variable :id
having the value ["123", "456", "789"]
.
As well, paths can end with two optional parts, *
and /?
. If it ends with a *
, it will match partially, returning the part of the path unmatched in the PATH_INFO value of the env. The part matched to will be returned in the SCRIPT_NAME. If it ends with /?
, then a trailing / on the path will be optionally matched for that specific route. As trailing /‘s are ignored by default, you probably don’t actually want to use this option that frequently.
Routes can also contain optional parts. There are surrounded with ( )
‘s. If you need to match on a bracket in the route itself, you can escape the parentheses with a backslash.
As well, options can be passed in that modify the route in further ways. See HttpRouter::Route#with_options for details. Typically, you want to add further options to the route by calling additional methods on it. See HttpRouter::Route for further details.
Returns the route object.
69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/http_router.rb', line 69 def add(*args, &app) uncompile opts = args.last.is_a?(Hash) ? args.pop : nil path = args.first route = route_class.new add_route route route.path = path if path route.process_opts(opts) if opts route.to(app) if app route end |
#add_route(route) ⇒ Object
81 82 83 84 85 |
# File 'lib/http_router.rb', line 81 def add_route(route) @routes << route @named_routes[route.name] << route if route.name route.router = self end |
#call(env, &callback) ⇒ Object Also known as: compiling_call
Rack compatible #call. If matching route is found, and dest
value responds to #call, processing will pass to the matched route. Otherwise, the default application will be called. The router will be available in the env under the key router
. And parameters matched will be available under the key router.params
.
140 141 142 143 |
# File 'lib/http_router.rb', line 140 def call(env, &callback) compile call(env, &callback) end |
#clone(klass = self.class) ⇒ Object
Creates a deep-copy of the router.
213 214 215 216 217 218 219 220 |
# File 'lib/http_router.rb', line 213 def clone(klass = self.class) cloned_router = klass.new(@options) @routes.each do |route| new_route = route.create_clone(cloned_router) cloned_router.add_route(new_route) end cloned_router end |
#default(app) ⇒ Object
Assigns the default application.
155 156 157 |
# File 'lib/http_router.rb', line 155 def default(app) @default_app = app end |
#extend_route(&blk) ⇒ Object
Extends the route class with custom features.
Example:
router = HttpRouter.new { extend_route { attr_accessor :controller } }
router.add('/foo', :controller => :foo).to{|env| [200, {}, ['foo!']]}
matches, other_methods = router.recognize(Rack::MockRequest.env_for('/foo'))
matches.first.route.controller
# ==> :foo
95 96 97 98 99 |
# File 'lib/http_router.rb', line 95 def extend_route(&blk) @route_class = Class.new(Route) if @route_class == Route @route_class.class_eval(&blk) @extended_route_class = nil end |
#get(path, opts = {}, &app) ⇒ Object
Adds a path that only responds to the request method GET
.
Returns the route object.
121 |
# File 'lib/http_router.rb', line 121 def get(path, opts = {}, &app); add_with_request_method(path, [:get, :head], opts, &app); end |
#ignore_trailing_slash? ⇒ Boolean
Ignore trailing slash feature enabled? See #initialize for details.
203 204 205 |
# File 'lib/http_router.rb', line 203 def ignore_trailing_slash? @ignore_trailing_slash end |
#inspect ⇒ Object
242 243 244 245 |
# File 'lib/http_router.rb', line 242 def inspect head = to_s "#{to_s}\n#{'=' * head.size}\n#{@root.inspect}" end |
#no_response(request, env) ⇒ Object
232 233 234 235 |
# File 'lib/http_router.rb', line 232 def no_response(request, env) request.acceptable_methods.empty? ? @default_app.call(env) : [405, {'Allow' => request.acceptable_methods.sort.join(", ")}, []] end |
#pass_on_response(response) ⇒ Object
This method defines what sort of responses are considered “passes”, and thus, route processing will continue. Override it to implement custom passing.
198 199 200 |
# File 'lib/http_router.rb', line 198 def pass_on_response(response) response[1]['X-Cascade'] == 'pass' end |
#path(route, *args) ⇒ Object Also known as: compiling_path
185 186 187 188 |
# File 'lib/http_router.rb', line 185 def path(route, *args) compile path(route, *args) end |
#process_destination_path(path, env) ⇒ Object
This method is invoked when a Path object gets called with an env. Override it to implement custom path processing.
192 193 194 |
# File 'lib/http_router.rb', line 192 def process_destination_path(path, env) path.route.dest.call(env) end |
#raw_call(env, &blk) ⇒ Object
281 282 283 284 285 286 287 288 289 290 |
# File 'lib/http_router.rb', line 281 def raw_call(env, &blk) rack_request = ::Rack::Request.new(env) request = Request.new(rack_request.path_info, rack_request) if blk @root.call(request, &blk) request else @root.call(request) or no_response(request, env) end end |
#raw_path(route, *args) ⇒ Object
273 274 275 276 277 278 279 |
# File 'lib/http_router.rb', line 273 def raw_path(route, *args) case route when Symbol then @named_routes.key?(route) && @named_routes[route].each{|r| path = r.path(*args); return path if path} when Route then return route.path(*args) end raise(InvalidRouteException.new "No route (path) could be generated for #{route.inspect}") end |
#raw_url(route, *args) ⇒ Object
257 258 259 260 261 262 263 |
# File 'lib/http_router.rb', line 257 def raw_url(route, *args) case route when Symbol then @named_routes.key?(route) && @named_routes[route].each{|r| url = r.url(*args); return url if url} when Route then return route.url(*args) end raise(InvalidRouteException.new "No route (url) could be generated for #{route.inspect}") end |
#raw_url_ns(route, *args) ⇒ Object
265 266 267 268 269 270 271 |
# File 'lib/http_router.rb', line 265 def raw_url_ns(route, *args) case route when Symbol then @named_routes.key?(route) && @named_routes[route].each{|r| url = r.url_ns(*args); return url if url} when Route then return route.url_ns(*args) end raise(InvalidRouteException.new "No route (url_ns) could be generated for #{route.inspect}") end |
#recognize(env, &callback) ⇒ Object
Performs recoginition without actually calling the application and returns an array of all matching routes or nil if no match was found.
125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/http_router.rb', line 125 def recognize(env, &callback) if callback request = call(env, &callback) [request.called?, request.acceptable_methods] else matches = [] callback ||= Proc.new {|match| matches << match} request = call(env, &callback) [matches.empty? ? nil : matches, request.acceptable_methods] end end |
#redirect_trailing_slash? ⇒ Boolean
Redirect trailing slash feature enabled? See #initialize for details.
208 209 210 |
# File 'lib/http_router.rb', line 208 def redirect_trailing_slash? @redirect_trailing_slash end |
#reset! ⇒ Object
Resets the router to a clean state.
147 148 149 150 151 152 |
# File 'lib/http_router.rb', line 147 def reset! uncompile @routes, @named_routes, @root = [], Hash.new{|h,k| h[k] = []}, Node::Root.new(self) @default_app = Proc.new{ |env| ::Rack::Response.new("Your request couldn't be found", 404).finish } @default_host, @default_port, @default_scheme = 'localhost', 80, 'http' end |
#rewrite_partial_path_info(env, request) ⇒ Object
222 223 224 225 |
# File 'lib/http_router.rb', line 222 def rewrite_partial_path_info(env, request) env['PATH_INFO'] = "/#{request.path.join('/')}" env['SCRIPT_NAME'] += request.rack_request.path_info[0, request.rack_request.path_info.size - env['PATH_INFO'].size] end |
#rewrite_path_info(env, request) ⇒ Object
227 228 229 230 |
# File 'lib/http_router.rb', line 227 def rewrite_path_info(env, request) env['SCRIPT_NAME'] += request.rack_request.path_info env['PATH_INFO'] = '' end |
#to_s ⇒ Object
237 238 239 240 |
# File 'lib/http_router.rb', line 237 def to_s compile "#<HttpRouter:0x#{object_id.to_s(16)} number of routes (#{routes.size}) ignore_trailing_slash? (#{ignore_trailing_slash?}) redirect_trailing_slash? (#{redirect_trailing_slash?})>" end |
#uncompile ⇒ Object
247 248 249 250 251 252 253 254 255 |
# File 'lib/http_router.rb', line 247 def uncompile return unless @compiled instance_eval "undef :path; alias :path :compiling_path undef :url; alias :url :compiling_url undef :url_ns; alias :url_ns :compiling_url_ns undef :call; alias :call :compiling_call", __FILE__, __LINE__ @root.uncompile @compiled = false end |
#url(route, *args) ⇒ Object Also known as: compiling_url
Generate a URL for a specified route. This will accept a list of variable values plus any other variable names named as a hash. This first value must be either the Route object or the name of the route.
Example:
router = HttpRouter.new
router.add('/:foo.:format', :name => :test).to{|env| [200, {}, []]}
router.path(:test, 123, 'html')
# ==> "/123.html"
router.path(:test, 123, :format => 'html')
# ==> "/123.html"
router.path(:test, :foo => 123, :format => 'html')
# ==> "/123.html"
router.path(:test, :foo => 123, :format => 'html', :fun => 'inthesun')
# ==> "/123.html?fun=inthesun"
173 174 175 176 |
# File 'lib/http_router.rb', line 173 def url(route, *args) compile url(route, *args) end |
#url_ns(route, *args) ⇒ Object Also known as: compiling_url_ns
179 180 181 182 |
# File 'lib/http_router.rb', line 179 def url_ns(route, *args) compile url_ns(route, *args) end |