Froze rails gems
[depot.git] / vendor / rails / actionpack / lib / action_controller / routing / route.rb
1 module ActionController
2 module Routing
3 class Route #:nodoc:
4 attr_accessor :segments, :requirements, :conditions, :optimise
5
6 def initialize(segments = [], requirements = {}, conditions = {})
7 @segments = segments
8 @requirements = requirements
9 @conditions = conditions
10
11 if !significant_keys.include?(:action) && !requirements[:action]
12 @requirements[:action] = "index"
13 @significant_keys << :action
14 end
15
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
21 @optimise = false
22 else
23 @optimise = true
24 end
25 end
26
27 # Indicates whether the routes should be optimised with the string interpolation
28 # version of the named routes methods.
29 def optimise?
30 @optimise && ActionController::Base::optimise_named_routes
31 end
32
33 def segment_keys
34 segments.collect do |segment|
35 segment.key if segment.respond_to? :key
36 end.compact
37 end
38
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
42 # values.
43 def build_query_string(hash, only_keys = nil)
44 elements = []
45
46 (only_keys || hash.keys).each do |key|
47 if value = hash[key]
48 elements << value.to_query(key)
49 end
50 end
51
52 elements.empty? ? '' : "?#{elements.sort * '&'}"
53 end
54
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.
57 #
58 # For example, +{:controller => 'pages', :action => 'show'} is the shell for the route:
59 #
60 # map.connect '/page/:id', :controller => 'pages', :action => 'show', :id => /\d+/
61 #
62 def parameter_shell
63 @parameter_shell ||= returning({}) do |shell|
64 requirements.each do |key, requirement|
65 shell[key] = requirement unless requirement.is_a? Regexp
66 end
67 end
68 end
69
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
72 # placed upon them.
73 def significant_keys
74 @significant_keys ||= returning([]) do |sk|
75 segments.each { |segment| sk << segment.key if segment.respond_to? :key }
76 sk.concat requirements.keys
77 sk.uniq!
78 end
79 end
80
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.
83 def defaults
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?
88 end
89 requirements.each do |key,req|
90 next if Regexp === req || req.nil?
91 hash[key] = req
92 end
93 end
94 end
95
96 def matches_controller_and_action?(controller, action)
97 prepare_matching!
98 (@controller_requirement.nil? || @controller_requirement === controller) &&
99 (@action_requirement.nil? || @action_requirement === action)
100 end
101
102 def to_s
103 @to_s ||= begin
104 segs = segments.inject("") { |str,s| str << s.to_s }
105 "%-6s %-40s %s" % [(conditions[:method] || :any).to_s.upcase, segs, requirements.inspect]
106 end
107 end
108
109 # TODO: Route should be prepared and frozen on initialize
110 def freeze
111 unless frozen?
112 write_generation!
113 write_recognition!
114 prepare_matching!
115
116 parameter_shell
117 significant_keys
118 defaults
119 to_s
120 end
121
122 super
123 end
124
125 private
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
130 end
131 nil
132 end
133
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}"
138
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 = {}"
142
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__})"
146
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
151 # query string.)
152
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__})"
155
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__})"
158 raw_method
159 end
160
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
166 end.compact * "\n"
167 end
168
169 # Produce a condition expression that will check the requirements of this route
170 # upon generation.
171 def generation_requirements
172 requirement_conditions = requirements.collect do |key, req|
173 if req.is_a? Regexp
174 value_regexp = Regexp.new "\\A#{req.to_s}\\Z"
175 "hash[:#{key}] && #{value_regexp.inspect} =~ options[:#{key}]"
176 else
177 "hash[:#{key}] == #{req.inspect}"
178 end
179 end
180 requirement_conditions * ' && ' unless requirement_conditions.empty?
181 end
182
183 def generation_structure
184 segments.last.string_structure segments[0..-2]
185 end
186
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"
192
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__})"
196 method_decl
197 end
198
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]
205 result
206 end
207
208 # Build the regular expression pattern that will match this route.
209 def recognition_pattern(wrap = true)
210 pattern = ''
211 segments.reverse_each do |segment|
212 pattern = segment.build_pattern pattern
213 end
214 wrap ? ("\\A" + pattern + "\\Z") : pattern
215 end
216
217 # Write the code to extract the parameters from a matched route.
218 def recognition_extraction
219 next_capture = 1
220 extraction = segments.collect do |segment|
221 x = segment.match_extraction(next_capture)
222 next_capture += segment.number_of_captures
223 x
224 end
225 extraction.compact
226 end
227
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)}"
234 end
235
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
244 end
245
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
251 end
252 end
253 end
254 end
255 end