rb). The Route#recognize method rewrites
itself:
class Route
def recognize(path, environment={})
write_recognition
recognize path, environment
end
end
The recognize method calls write_recognition, which processes the route logic and
creates a compiled version of the route. The write_recognition method then overwrites
the definition of recognize with that definition. The last line in the original
recognize method then calls recognize (which has been replaced by the compiled
version) with the original arguments. This way, the route is compiled on the first call
to recognize. Any subsequent calls use the compiled version, rather than having to
reparse the routing DSL and go through the routing logic again.
Here is the body of the write_recognition method:
def write_recognition
# Create an if structure to extract the params from a match if it occurs.
body = "params = parameter_shell.dup\n#{recognition_extraction * "\n"}\nparams"
body = "if #{recognition_conditions.join(" && ")}\n#{body}\nend"
# Build the method declaration and compile it
method_decl = "def recognize(path, env={})\n#{body}\nend"
instance_eval method_decl, "generated code (#{__FILE_ _}:#{_ _LINE_ _})"
method_decl
end
The local variable body is built up with the compiled route code. It is wrapped in a
method declaration that overwrites recognize. For the default route:
map.connect ':controller/:action/:id'
write_recognition generates code looking like this:
def recognize(path, env={})
if (match = /(long regex)/.
Pages:
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79