Class: Routes
Overview
The Routes class takes a set of routes and sets up methods to go from a url to params, and params to url. routes do
get "/about", _view: 'about'
get "/blog/{_id}/edit", _view: 'blog/edit', _action: 'edit'
get "/blog/{_id}", _view: 'blog/show', _action: 'show'
get "/blog", _view: 'blog'
get "/blog/new", _view: 'blog/new', _action: 'new'
get "/cool/{_name}", _view: 'cool'
end
Using the routes above, we would generate the following:
}
– nil represents a terminal – * represents any match – a number for a parameter means use the value in that number section
}
}
Match for params ]
Instance Method Summary collapse
- #define(&block) ⇒ Object
-
#get(path, params = {}) ⇒ Object
Add a route.
-
#initialize ⇒ Routes
constructor
A new instance of Routes.
-
#params_to_url(test_params) ⇒ Object
Takes in params and generates a path and the remaining params that should be shown in the url.
-
#url_to_params(path) ⇒ Object
Takes in a path and returns the matching params.
Constructor Details
#initialize ⇒ Routes
Returns a new instance of Routes.
42 43 44 45 46 47 48 49 50 51 |
# File 'lib/volt/router/routes.rb', line 42 def initialize # Paths where there are no bindings (an optimization) @direct_routes = {} # Paths with bindings @indirect_routes = {} # Matcher for going from params to url @param_matches = [] end |
Instance Method Details
#define(&block) ⇒ Object
53 54 55 56 57 |
# File 'lib/volt/router/routes.rb', line 53 def define(&block) instance_eval(&block) return self end |
#get(path, params = {}) ⇒ Object
Add a route
60 61 62 63 64 65 66 67 68 69 |
# File 'lib/volt/router/routes.rb', line 60 def get(path, params={}) params = params.symbolize_keys if has_binding?(path) add_indirect_path(path, params) else @direct_routes[path] = params end add_param_matcher(path, params) end |
#params_to_url(test_params) ⇒ Object
Takes in params and generates a path and the remaining params that should be shown in the url. The extra “unused” params will be tacked onto the end of the url ?param1=value1, etc…
returns the url and new params, or nil, nil if no match is found.
76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/volt/router/routes.rb', line 76 def params_to_url(test_params) @param_matches.each do |param_matcher| # TODO: Maybe a deep dup? result, new_params = check_params_match(test_params.dup, param_matcher[0]) if result return param_matcher[1].call(new_params) end end return nil, nil end |
#url_to_params(path) ⇒ Object
Takes in a path and returns the matching params. returns params as a hash
91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/volt/router/routes.rb', line 91 def url_to_params(path) # First try a direct match result = @direct_routes[path] return result if result # Next, split the url and walk the sections parts = url_parts(path) result = match_path(parts, parts, @indirect_routes) return result end |