Routing (path rewriting) functionality. Due to the power of Nitro’s intelligent dispatching mechanism, routing is almost never used! It is only needed for really special urls.
| [RW] | rules | The routing rules. |
Alias for #add_rule
Alias for #add_rule
Add a routing rule
Examples
r.add_rule(:match => %r{^~(.*)}, :controller => User::Controller, :action => view, :params => [:name])
[ show source ]
# File lib/raw/dispatcher/router.rb, line 21
21: def add_rule(rule)
22: @rules ||= []
23: @rules << rule
24: end
Convert routes defined with annotations to normal routes. Typically called after a new Controller is mounted.
Example of routing through annotations
def view_user
"params: #{request[:id]} and #{request[:mode]}"
end ann :view_user, :match => /user_(\d*)_(*?)\.html/, :params => [:id, :mode]
[ show source ]
# File lib/raw/dispatcher/router.rb, line 52
52: def add_rules_from_annotations(controller)
53: for m in controller.action_methods
54: m = m.to_sym
55: if match = controller.ann(m, :match)
56: add_rule(:match => match, :controller => controller, :action => m, :params => controller.ann(m, :params))
57: end
58: end
59: end
Try to decode the given path by applying routing rules. If routing is possible return the transformed path, else return the input path.
[ show source ]
# File lib/raw/dispatcher/router.rb, line 65
65: def decode_route(path)
66: # Front end server (for example Apache) some times escape
67: # the uri. REMOVE THIS: unescape in the adapter!!
68: path = CGI.unescape(path)
69:
70: for rule in @rules
71: unless transformer = rule[:transformer]
72: transformer = rule[:transformer] = rule_transformer(rule)
73: end
74:
75: if path.gsub!(rule[:match], transformer)
76: Logger.debug "Rewriting '#{path}'." if $DBG
77: break;
78: end
79: end
80:
81: return path
82: end
Encodes a [controller, action, params] tupple into a path. Returns false if no encoding is possible.
[ show source ]
# File lib/raw/dispatcher/router.rb, line 88
88: def encode_route(controller, action, *params)
89: if rule = @rules.find { |r| (r[:controller] == controller) and (r[:action] == action) }
90: path = rule[:match].source
91:
92: (params.size / 2).times do |i|
93: val = params[i + i + 1]
94: path.sub!(/\(.*?\)/, val.to_s)
95: end
96:
97: return path
98: end
99:
100: return false
101: end
Alias for #decode_route
Generate the transformer string for the match gsub.
[ show source ]
# File lib/raw/dispatcher/router.rb, line 30
30: def rule_transformer(rule)
31: transformer = "#{rule[:controller].mount_path}/#{rule[:action]}"
32:
33: if params = rule[:params]
34: params.size.times do |i|
35: transformer << "/#{i+1}"
36: end
37: end
38:
39: return transformer
40: end