public
Description: Ruby on Rails
Homepage: http://rubyonrails.org
Clone URL: git://github.com/rails/rails.git
Search Repo:
Nicholas Seckar (author)
Sun Aug 06 23:09:18 -0700 2006
commit  33bc251ede4f77c4343af83d8996a37af646ccd1
tree    e5895e074c4c33072bf629dea58b8389fe711530
parent  e7e464a97fe52d5ac0712c29d38637bab644ca2d
rails / actionpack / lib / action_controller / routing.rb
100644 720 lines (597 sloc) 24.465 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
module ActionController
  module Routing #:nodoc:
    class << self
      def expiry_hash(options, recall)
        k = v = nil
        expire_on = {}
        options.each {|k, v| expire_on[k] = ((rcv = recall[k]) && (rcv != v))}
        expire_on
      end
 
      def extract_parameter_value(parameter) #:nodoc:
        CGI.escape((parameter.respond_to?(:to_param) ? parameter.to_param : parameter).to_s)
      end
      def controller_relative_to(controller, previous)
        if controller.nil? then previous
        elsif controller[0] == ?/ then controller[1..-1]
        elsif %r{^(.*)/} =~ previous then "#{$1}/#{controller}"
        else controller
        end
      end
 
      def treat_hash(hash, keys_to_delete = [])
        k = v = nil
        hash.each do |k, v|
          if v then hash[k] = (v.respond_to? :to_param) ? v.to_param.to_s : v.to_s
          else
            hash.delete k
            keys_to_delete << k
          end
        end
        hash
      end
      
      def test_condition(expression, condition)
        case condition
          when String then "(#{expression} == #{condition.inspect})"
          when Regexp then
            condition = Regexp.new("^#{condition.source}$") unless /^\^.*\$$/ =~ condition.source
            "(#{condition.inspect} =~ #{expression})"
          when Array then
            conds = condition.collect do |condition|
              cond = test_condition(expression, condition)
              (cond[0, 1] == '(' && cond[-1, 1] == ')') ? cond : "(#{cond})"
            end
            "(#{conds.join(' || ')})"
          when true then expression
          when nil then "! #{expression}"
          else
            raise ArgumentError, "Valid criteria are strings, regular expressions, true, or nil"
        end
      end
    end
 
    class Component #:nodoc:
      def dynamic?() false end
      def optional?() false end
 
      def key() nil end
  
      def self.new(string, *args)
        return super(string, *args) unless self == Component
        case string
          when ':controller' then ControllerComponent.new(:controller, *args)
          when /^:(\w+)$/ then DynamicComponent.new($1, *args)
          when /^\*(\w+)$/ then PathComponent.new($1, *args)
          else StaticComponent.new(string, *args)
        end
      end
    end
 
    class StaticComponent < Component #:nodoc:
      attr_reader :value
  
      def initialize(value)
        @value = value
      end
 
      def write_recognition(g)
        g.if_next_matches(value) do |gp|
          gp.move_forward {|gpp| gpp.continue}
        end
      end
 
      def write_generation(g)
        g.add_segment(value) {|gp| gp.continue }
      end
    end
 
    class DynamicComponent < Component #:nodoc:
      attr_reader :key, :default
      attr_accessor :condition
  
      def dynamic?() true end
      def optional?() @optional end
 
      def default=(default)
        @optional = true
        @default = default
      end
    
      def initialize(key, options = {})
        @key = key.to_sym
        @optional = false
        default, @condition = options[:default], options[:condition]
        self.default = default if options.key?(:default)
      end
 
      def default_check(g)
        presence = "#{g.hash_value(key, !! default)}"
        if default
           "!(#{presence} && #{g.hash_value(key, false)} != #{default.to_s.inspect})"
        else
          "! #{presence}"
        end
      end
  
      def write_generation(g)
        wrote_dropout = write_dropout_generation(g)
        write_continue_generation(g, wrote_dropout)
      end
 
      def write_dropout_generation(g)
        return false unless optional? && g.after.all? {|c| c.optional?}
    
        check = [default_check(g)]
        gp = g.dup # Use another generator to write the conditions after the first &&
        # We do this to ensure that the generator will not assume x_value is set. It will
        # not be set if it follows a false condition -- for example, false && (x = 2)
        
        check += gp.after.map {|c| c.default_check gp}
        gp.if(check.join(' && ')) { gp.finish } # If this condition is met, we stop here
        true
      end
 
      def write_continue_generation(g, use_else)
        test = Routing.test_condition(g.hash_value(key, true, default), condition || true)
        check = (use_else && condition.nil? && default) ? [:else] : [use_else ? :elsif : :if, test]
    
        g.send(*check) do |gp|
          gp.expire_for_keys(key) unless gp.after.empty?
          add_segments_to(gp) {|gpp| gpp.continue}
        end
      end
 
      def add_segments_to(g)
        g.add_segment(%(\#{CGI.escape(#{g.hash_value(key, true, default)})})) {|gp| yield gp}
      end
  
      def recognition_check(g)
        test_type = [true, nil].include?(condition) ? :presence : :constraint
    
        prefix = condition.is_a?(Regexp) ? "#{g.next_segment(true)} && " : ''
        check = prefix + Routing.test_condition(g.next_segment(true), condition || true)
    
        g.if(check) {|gp| yield gp, test_type}
      end
  
      def write_recognition(g)
        test_type = nil
        recognition_check(g) do |gp, test_type|
          assign_result(gp) {|gpp| gpp.continue}
        end
    
        if optional? && g.after.all? {|c| c.optional?}
          call = (test_type == :presence) ? [:else] : [:elsif, "! #{g.next_segment(true)}"]
       
          g.send(*call) do |gp|
            assign_default(gp)
            gp.after.each {|c| c.assign_default(gp)}
            gp.finish(false)
          end
        end
      end
 
      def assign_result(g, with_default = false)
        g.result key, "CGI.unescape(#{g.next_segment(true, with_default ? default : nil)})"
        g.move_forward {|gp| yield gp}
      end
 
      def assign_default(g)
        g.constant_result key, default unless default.nil?
      end
    end
 
    class ControllerComponent < DynamicComponent #:nodoc:
      def key() :controller end
 
      def add_segments_to(g)
        g.add_segment(%(\#{#{g.hash_value(key, true, default)}})) {|gp| yield gp}
      end
    
      def recognition_check(g)
        g << "controller_result = ::ActionController::Routing::ControllerComponent.traverse_to_controller(#{g.path_name}, #{g.index_name})"
        g.if('controller_result') do |gp|
          gp << 'controller_value, segments_to_controller = controller_result'
          if condition
            gp << "controller_path = #{gp.path_name}[#{gp.index_name},segments_to_controller].join('/')"
            gp.if(Routing.test_condition("controller_path", condition)) do |gpp|
              gpp.move_forward('segments_to_controller') {|gppp| yield gppp, :constraint}
            end
          else
            gp.move_forward('segments_to_controller') {|gpp| yield gpp, :constraint}
          end
        end
      end
 
      def assign_result(g)
        g.result key, 'controller_value'
        yield g
      end
 
      def assign_default(g)
        ControllerComponent.assign_controller(g, default)
      end
  
      class << self
        def assign_controller(g, controller)
          expr = "::#{controller.split('/').collect {|c| c.camelize}.join('::')}Controller"
          g.result :controller, expr, true
        end
        
        def file_kinds(kind)
          ((@file_kinds ||= []) << kind).uniq! || @file_kinds
        end
        
        def traverse_to_controller(segments, start_at = 0)
          mod = ::Object
          length = segments.length
          index = start_at
          mod_name = controller_name = segment = nil
          while index < length
            return nil unless /\A[A-Za-z][A-Za-z\d_]*\Z/ =~ (segment = segments[index])
            index += 1
            
            file_kinds :app
            mod_name = segment.camelize
            controller_name = "#{mod_name}Controller"
            path_suffix = File.join(segments[start_at..(index - 1)])
            next_mod = nil
            
            # If the controller is already present, or if we load it, return it.
            if mod.const_defined?(controller_name) || attempt_load(mod, controller_name, path_suffix + "_controller") == :defined
              controller = mod.const_get(controller_name)
              return nil unless controller.is_a?(Class) && controller.ancestors.include?(ActionController::Base) # it's not really a controller?
              return [controller, (index - start_at)]
            end
            
            # No controller? Look for the module
            if mod.const_defined? mod_name
              next_mod = mod.send(:const_get, mod_name)
              next_mod = nil unless next_mod.is_a?(Module)
            else
              # Try to load a file that defines the module we want.
              case attempt_load(mod, mod_name, path_suffix)
                when :defined then next_mod = mod.const_get mod_name
                when :dir then # We didn't find a file, but there's a dir.
                  next_mod = Module.new # So create a module for the directory
                  mod.send :const_set, mod_name, next_mod
                else
                  return nil
              end
            end
            mod = next_mod
            
            return nil unless mod && mod.is_a?(Module)
          end
          nil
        end
        
      protected
        def safe_load_paths #:nodoc:
          if defined?(RAILS_ROOT)
            $LOAD_PATH.select do |base|
              base = File.expand_path(base)
              extended_root = File.expand_path(RAILS_ROOT)
              base.match(/\A#{Regexp.escape(extended_root)}\/*#{file_kinds(:lib) * '|'}/) || base =~ %r{rails-[\d.]+/builtin}
            end
          else
            $LOAD_PATH
          end
        end
        
        def attempt_load(mod, const_name, path)
          has_dir = false
          safe_load_paths.each do |load_path|
            full_path = File.join(load_path, path)
            file_path = full_path + '.rb'
            if File.file?(file_path) # Found a .rb file? Load it up
              require_dependency(file_path)
              return :defined if mod.const_defined? const_name
            else
              has_dir ||= File.directory?(full_path)
            end
          end
          return (has_dir ? :dir : nil)
        end
      end
    end
 
    class PathComponent < DynamicComponent #:nodoc:
      def optional?() true end
      def default() [] end
      def condition() nil end
 
      def default=(value)
        raise RoutingError, "All path components have an implicit default of []" unless value == []
      end
  
      def write_generation(g)
        raise RoutingError, 'Path components must occur last' unless g.after.empty?
        g.if("#{g.hash_value(key, true)} && ! #{g.hash_value(key, true)}.empty?") do
          g << "#{g.hash_value(key, true)} = #{g.hash_value(key, true)}.join('/') unless #{g.hash_value(key, true)}.is_a?(String)"
          g.add_segment("\#{CGI.escape_skipping_slashes(#{g.hash_value(key, true)})}") {|gp| gp.finish }
        end
        g.else { g.finish }
      end
  
      def write_recognition(g)
        raise RoutingError, "Path components must occur last" unless g.after.empty?
    
        start = g.index_name
        start = "(#{start})" unless /^\w+$/ =~ start
    
        value_expr = "#{g.path_name}[#{start}..-1] || []"
        g.result key, "ActionController::Routing::PathComponent::Result.new_escaped(#{value_expr})"
        g.finish(false)
      end
  
      class Result < ::Array #:nodoc:
        def to_s() join '/' end
        def self.new_escaped(strings)
          new strings.collect {|str| CGI.unescape str}
        end
      end
    end
 
    class Route #:nodoc:
      attr_accessor :components, :known
      attr_reader :path, :options, :keys, :defaults
  
      def initialize(path, options = {})
        @path, @options = path, options
    
        initialize_components path
        defaults, conditions = initialize_hashes options.dup
        @defaults = defaults.dup
        configure_components(defaults, conditions)
        add_default_requirements
        initialize_keys
      end
  
      def inspect
        "<#{self.class} #{path.inspect}, #{options.inspect[1..-1]}>"
      end
  
      def write_generation(generator = CodeGeneration::GenerationGenerator.new)
        generator.before, generator.current, generator.after = [], components.first, (components[1..-1] || [])
 
        if known.empty? then generator.go
        else
          # Alter the conditions to allow :action => 'index' to also catch :action => nil
          altered_known = known.collect do |k, v|
            if k == :action && v== 'index' then [k, [nil, 'index']]
            else [k, v]
            end