1 module ActionController
4 attr_accessor
:segments, :requirements, :conditions, :optimise
6 def initialize(segments
= [], requirements
= {}, conditions
= {})
8 @requirements = requirements
9 @conditions = conditions
11 if !significant_keys
.include?(:action) && !requirements
[:action]
12 @requirements[:action] = "index"
13 @significant_keys << :action
16 # Routes cannot use the current string interpolation method
17 # if there are user-supplied <tt>:requirements</tt> as the interpolation
18 # code won't raise RoutingErrors when generating
19 has_requirements
= @segments.detect
{ |segment
| segment
.respond_to
?(:regexp) && segment
.regexp
}
20 if has_requirements
|| @requirements.keys
.to_set
!= Routing
::ALLOWED_REQUIREMENTS_FOR_OPTIMISATION
27 # Indicates whether the routes should be optimised with the string interpolation
28 # version of the named routes methods.
30 @optimise && ActionController
::Base::optimise_named_routes
34 segments
.collect
do |segment
|
35 segment
.key
if segment
.respond_to
? :key
39 # Build a query string from the keys of the given hash. If +only_keys+
40 # is given (as an array), only the keys indicated will be used to build
41 # the query string. The query string will correctly build array parameter
43 def build_query_string(hash
, only_keys
= nil)
46 (only_keys
|| hash
.keys
).each
do |key
|
48 elements
<< value
.to_query(key
)
52 elements
.empty
? ? '' : "?#{elements.sort * '&'}"
55 # A route's parameter shell contains parameter values that are not in the
56 # route's path, but should be placed in the recognized hash.
58 # For example, +{:controller => 'pages', :action => 'show'} is the shell for the route:
60 # map.connect '/page/:id', :controller => 'pages', :action => 'show', :id => /\d+/
63 @parameter_shell ||= returning({}) do |shell
|
64 requirements
.each
do |key
, requirement
|
65 shell
[key
] = requirement
unless requirement
.is_a
? Regexp
70 # Return an array containing all the keys that are used in this route. This
71 # includes keys that appear inside the path, and keys that have requirements
74 @significant_keys ||= returning([]) do |sk
|
75 segments
.each
{ |segment
| sk
<< segment
.key
if segment
.respond_to
? :key }
76 sk
.concat requirements
.keys
81 # Return a hash of key/value pairs representing the keys in the route that
82 # have defaults, or which are specified by non-regexp requirements.
84 @defaults ||= returning({}) do |hash
|
85 segments
.each
do |segment
|
86 next unless segment
.respond_to
? :default
87 hash
[segment
.key
] = segment
.default
unless segment
.default
.nil?
89 requirements
.each
do |key
,req
|
90 next if Regexp
=== req
|| req
.nil?
96 def matches_controller_and_action
?(controller
, action
)
98 (@controller_requirement.nil? || @controller_requirement === controller
) &&
99 (@action_requirement.nil? || @action_requirement === action
)
104 segs
= segments
.inject("") { |str
,s
| str
<< s
.to_s
}
105 "%-6s %-40s %s" % [(conditions
[:method] || :any).to_s
.upcase
, segs
, requirements
.inspect
]
109 # TODO: Route should be prepared and frozen on initialize
126 def requirement_for(key
)
127 return requirements
[key
] if requirements
.key
? key
128 segments
.each
do |segment
|
129 return segment
.regexp
if segment
.respond_to
?(:key) && segment
.key
== key
134 # Write and compile a +generate+ method for this Route.
135 def write_generation
!
136 # Build the main body of the generation
137 body
= "expired = false\n#{generation_extraction}\n#{generation_structure}"
139 # If we have conditions that must be tested first, nest the body inside an if
140 body
= "if #{generation_requirements}\n#{body}\nend" if generation_requirements
141 args
= "options, hash, expire_on = {}"
143 # Nest the body inside of a def block, and then compile it.
144 raw_method
= method_decl
= "def generate_raw(#{args})\npath = begin\n#{body}\nend\n[path, hash]\nend"
145 instance_eval method_decl
, "generated code (#{__FILE__}:#{__LINE__})"
147 # expire_on.keys == recall.keys; in other words, the keys in the expire_on hash
148 # are the same as the keys that were recalled from the previous request. Thus,
149 # we can use the expire_on.keys to determine which keys ought to be used to build
150 # the query string. (Never use keys from the recalled request when building the
153 method_decl
= "def generate(#{args})\npath, hash = generate_raw(options, hash, expire_on)\nappend_query_string(path, hash, extra_keys(options))\nend"
154 instance_eval method_decl
, "generated code (#{__FILE__}:#{__LINE__})"
156 method_decl
= "def generate_extras(#{args})\npath, hash = generate_raw(options, hash, expire_on)\n[path, extra_keys(options)]\nend"
157 instance_eval method_decl
, "generated code (#{__FILE__}:#{__LINE__})"
161 # Build several lines of code that extract values from the options hash. If any
162 # of the values are missing or rejected then a return will be executed.
163 def generation_extraction
164 segments
.collect
do |segment
|
165 segment
.extraction_code
169 # Produce a condition expression that will check the requirements of this route
171 def generation_requirements
172 requirement_conditions
= requirements
.collect
do |key
, req
|
174 value_regexp
= Regexp
.new
"\\A#{req.to_s}\\Z"
175 "hash[:#{key}] && #{value_regexp.inspect} =~ options[:#{key}]"
177 "hash[:#{key}] == #{req.inspect}"
180 requirement_conditions
* ' && ' unless requirement_conditions
.empty
?
183 def generation_structure
184 segments
.last
.string_structure segments
[0..-2]
187 # Write and compile a +recognize+ method for this Route.
188 def write_recognition
!
189 # Create an if structure to extract the params from a match if it occurs.
190 body
= "params = parameter_shell.dup\n#{recognition_extraction * "\n"}\nparams"
191 body
= "if #{recognition_conditions.join(" && ")}\n#{body}\nend"
193 # Build the method declaration and compile it
194 method_decl
= "def recognize(path, env = {})\n#{body}\nend"
195 instance_eval method_decl
, "generated code (#{__FILE__}:#{__LINE__})"
199 # Plugins may override this method to add other conditions, like checks on
200 # host, subdomain, and so forth. Note that changes here only affect route
201 # recognition, not generation.
202 def recognition_conditions
203 result
= ["(match = #{Regexp.new(recognition_pattern).inspect}.match(path))"]
204 result
<< "[conditions[:method]].flatten.include?(env[:method])" if conditions
[:method]
208 # Build the regular expression pattern that will match this route.
209 def recognition_pattern(wrap
= true)
211 segments
.reverse_each
do |segment
|
212 pattern
= segment
.build_pattern pattern
214 wrap
? ("\\A" + pattern
+ "\\Z") : pattern
217 # Write the code to extract the parameters from a matched route.
218 def recognition_extraction
220 extraction
= segments
.collect
do |segment
|
221 x
= segment
.match_extraction(next_capture
)
222 next_capture
+= segment
.number_of_captures
228 # Generate the query string with any extra keys in the hash and append
229 # it to the given path, returning the new path.
230 def append_query_string(path
, hash
, query_keys
= nil)
231 return nil unless path
232 query_keys
||= extra_keys(hash
)
233 "#{path}#{build_query_string(hash, query_keys)}"
236 # Determine which keys in the given hash are "extra". Extra keys are
237 # those that were not used to generate a particular route. The extra
238 # keys also do not include those recalled from the prior request, nor
239 # do they include any keys that were implied in the route (like a
240 # <tt>:controller</tt> that is required, but not explicitly used in the
241 # text of the route.)
242 def extra_keys(hash
, recall
= {})
243 (hash
|| {}).keys
.map
{ |k
| k
.to_sym
} - (recall
|| {}).keys
- significant_keys
246 def prepare_matching
!
247 unless defined? @matching_prepared
248 @controller_requirement = requirement_for(:controller)
249 @action_requirement = requirement_for(:action)
250 @matching_prepared = true