mapper.rb 64.0 KB
Newer Older
1
require 'active_support/core_ext/hash/except'
B
Bogdan Gusiev 已提交
2
require 'active_support/core_ext/hash/reverse_merge'
3
require 'active_support/core_ext/hash/slice'
S
Santiago Pastorino 已提交
4
require 'active_support/core_ext/enumerable'
5
require 'active_support/core_ext/array/extract_options'
6
require 'active_support/core_ext/module/remove_method'
7
require 'active_support/inflector'
8
require 'action_dispatch/routing/redirection'
9

J
Joshua Peek 已提交
10 11
module ActionDispatch
  module Routing
J
Joshua Peek 已提交
12
    class Mapper
13
      URL_OPTIONS = [:protocol, :subdomain, :domain, :host, :port]
14
      SCOPE_OPTIONS = [:path, :shallow_path, :as, :shallow_prefix, :module,
15 16
                       :controller, :action, :path_names, :constraints,
                       :shallow, :blocks, :defaults, :options]
17

18
      class Constraints #:nodoc:
19
        attr_reader :app, :constraints
20

21
        def initialize(app, constraints, request, dispatcher_p, redirect_p)
22 23 24 25
          # Unwrap Constraints objects.  I don't actually think it's possible
          # to pass a Constraints object to this constructor, but there were
          # multiple places that kept testing children of this object.  I
          # *think* they were just being defensive, but I have no idea.
26
          if app.is_a?(self.class)
27 28 29 30
            constraints += app.constraints
            app = app.app
          end

31 32
          @dispatcher = dispatcher_p
          @redirect   = redirect_p
33

34
          @app, @constraints, @request = app, constraints, request
35 36
        end

37
        def dispatcher?; @dispatcher; end
38
        def redirect?; @redirect; end
39

40
        def matches?(req)
41 42 43
          @constraints.all? do |constraint|
            (constraint.respond_to?(:matches?) && constraint.matches?(req)) ||
              (constraint.respond_to?(:call) && constraint.call(*constraint_args(constraint, req)))
G
Gosha Arinich 已提交
44
          end
45 46
        end

47 48
        def serve(req)
          matches?(req) ? @app.call(req.env) : [ 404, {'X-Cascade' => 'pass'}, [] ]
49 50
        ensure
          req.reset_parameters
51
        end
52 53 54

        private
          def constraint_args(constraint, request)
55
            constraint.arity == 1 ? [request] : [request.path_parameters, request]
56
          end
57 58
      end

59
      class Mapping #:nodoc:
60
        IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix, :format]
61
        ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
62
        WILDCARD_PATH = %r{\*([^/\)]+)\)?$}
63

64
        attr_reader :scope, :path, :options, :requirements, :conditions, :defaults
65
        attr_reader :to, :default_controller, :default_action
66

67
        def initialize(set, scope, path, options)
68
          @set, @scope, @path = set, scope, path
69
          @requirements, @conditions, @defaults = {}, {}, {}
70

71 72 73 74 75 76
          options = scope[:options].merge(options) if scope[:options]
          @to                 = options[:to]
          @default_controller = options[:controller] || scope[:controller]
          @default_action     = options[:action] || scope[:action]

          @options = normalize_options!(options)
77
          normalize_path!
78 79
          normalize_requirements!
          normalize_conditions!
80
          normalize_defaults!
81
        end
J
Joshua Peek 已提交
82

83
        def to_route
84
          [ app, conditions, requirements, defaults, options[:as], options[:anchor] ]
85
        end
J
Joshua Peek 已提交
86

87
        private
88

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
          def normalize_path!
            raise ArgumentError, "path is required" if @path.blank?
            @path = Mapper.normalize_path(@path)

            if required_format?
              @path = "#{@path}.:format"
            elsif optional_format?
              @path = "#{@path}(.:format)"
            end
          end

          def required_format?
            options[:format] == true
          end

          def optional_format?
            options[:format] != false && !path.include?(':format') && !path.end_with?('/')
          end

108
          def normalize_options!(options)
109 110 111 112
            path_without_format = path.sub(/\(\.:format\)$/, '')

            # Add a constraint for wildcard route to make it non-greedy and match the
            # optional format part of the route by default
113 114
            if path_without_format.match(WILDCARD_PATH) && options[:format] != false
              options[$1.to_sym] ||= /.+?/
115 116 117 118 119 120 121 122 123
            end

            if path_without_format.match(':controller')
              raise ArgumentError, ":controller segment is not allowed within a namespace block" if scope[:module]

              # Add a default constraint for :controller path segments that matches namespaced
              # controllers with default routes like :controller/:action/:id(.:format), e.g:
              # GET /admin/products/show/1
              # => { controller: 'admin/products', action: 'show', id: '1' }
124
              options[:controller] ||= /.+?/
125
            end
126

127
            options.merge!(default_controller_and_action)
128 129 130 131 132
          end

          def normalize_requirements!
            constraints.each do |key, requirement|
              next unless segment_keys.include?(key) || key == :controller
Y
Yves Senn 已提交
133
              verify_regexp_requirement(requirement) if requirement.is_a?(Regexp)
134
              @requirements[key] = requirement
135
            end
136

137
            if options[:format] == true
138
              @requirements[:format] ||= /.+/
139 140 141 142 143
            elsif Regexp === options[:format]
              @requirements[:format] = options[:format]
            elsif String === options[:format]
              @requirements[:format] = Regexp.compile(options[:format])
            end
144
          end
145

Y
Yves Senn 已提交
146 147 148 149 150 151 152 153 154 155
          def verify_regexp_requirement(requirement)
            if requirement.source =~ ANCHOR_CHARACTERS_REGEX
              raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
            end

            if requirement.multiline?
              raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}"
            end
          end

156 157 158
          def normalize_defaults!
            @defaults.merge!(scope[:defaults]) if scope[:defaults]
            @defaults.merge!(options[:defaults]) if options[:defaults]
159

160
            options.each do |key, default|
A
Akshay Vishnoi 已提交
161 162 163
              unless Regexp === default || IGNORE_OPTIONS.include?(key)
                @defaults[key] = default
              end
164 165
            end

166 167
            if options[:constraints].is_a?(Hash)
              options[:constraints].each do |key, default|
A
Akshay Vishnoi 已提交
168 169 170
                if URL_OPTIONS.include?(key) && (String === default || Fixnum === default)
                  @defaults[key] ||= default
                end
171
              end
172 173
            elsif options[:constraints]
              verify_callable_constraint(options[:constraints])
174 175
            end

176 177 178 179
            if Regexp === options[:format]
              @defaults[:format] = nil
            elsif String === options[:format]
              @defaults[:format] = options[:format]
180
            end
181
          end
182

183
          def verify_callable_constraint(callable_constraint)
184 185 186
            unless callable_constraint.respond_to?(:call) || callable_constraint.respond_to?(:matches?)
              raise ArgumentError, "Invalid constraint: #{callable_constraint.inspect} must respond to :call or :matches?"
            end
187 188
          end

189
          def normalize_conditions!
190
            @conditions[:path_info] = path
191

192
            constraints.each do |key, condition|
A
Akshay Vishnoi 已提交
193 194 195
              unless segment_keys.include?(key) || key == :controller
                @conditions[key] = condition
              end
196
            end
J
Joshua Peek 已提交
197

198
            required_defaults = []
199
            options.each do |key, required_default|
A
Akshay Vishnoi 已提交
200
              unless segment_keys.include?(key) || IGNORE_OPTIONS.include?(key) || Regexp === required_default
201
                required_defaults << key
A
Akshay Vishnoi 已提交
202
              end
203
            end
204
            @conditions[:required_defaults] = required_defaults
205

206 207 208 209
            via_all = options.delete(:via) if options[:via] == :all

            if !via_all && options[:via].blank?
              msg = "You should not use the `match` method in your router without specifying an HTTP method.\n" \
210 211
                    "If you want to expose your action to both GET and POST, add `via: [:get, :post]` option.\n" \
                    "If you want to expose your action to GET, use `get` in the router:\n" \
212 213 214
                    "  Instead of: match \"controller#action\"\n" \
                    "  Do: get \"controller#action\""
              raise msg
215
            end
216

217
            if via = options[:via]
218
              @conditions[:request_method] = Array(via).map { |m| m.to_s.dasherize.upcase }
219 220 221
            end
          end

222
          def app
223 224 225
            dispatcher_p = false
            redirect     = false

226 227 228 229 230
            # Unwrap any constraints so we can see what's inside for route generation.
            # This allows the formatter to skip over any mounted applications or redirects
            # that shouldn't be matched when using a url_for without a route name.
            if to.respond_to?(:call)
              endpoint = to
231
              redirect = Redirect === endpoint
232 233 234 235
            else
              dispatcher_p = true
              endpoint = dispatcher
            end
236

237
            if blocks.any?
238
              Constraints.new(endpoint, blocks, @set.request_class, dispatcher_p, redirect)
239
            else
240
              Constraints.new(endpoint, blocks, @set.request_class, dispatcher_p, redirect)
241
            end
242 243
          end

244
          def default_controller_and_action
245
            if to.respond_to?(:call)
246 247
              { }
            else
248
              if to.is_a?(String)
249
                controller, action = to.split('#')
250 251
              elsif to.is_a?(Symbol)
                action = to.to_s
252
              end
J
Joshua Peek 已提交
253

254 255
              controller ||= default_controller
              action     ||= default_action
256

257 258 259 260 261 262
              if @scope[:module] && !controller.is_a?(Regexp)
                if controller =~ %r{\A/}
                  controller = controller[1..-1]
                else
                  controller = [@scope[:module], controller].compact.join("/").presence
                end
263
              end
264

265 266 267 268
              if controller.is_a?(String) && controller =~ %r{\A/}
                raise ArgumentError, "controller name should not start with a slash"
              end

269 270
              controller = controller.to_s unless controller.is_a?(Regexp)
              action     = action.to_s     unless action.is_a?(Regexp)
271

272
              if controller.blank? && segment_keys.exclude?(:controller)
273 274
                message = "Missing :controller key on routes definition, please check your routes."
                raise ArgumentError, message
275
              end
J
Joshua Peek 已提交
276

277
              if action.blank? && segment_keys.exclude?(:action)
278 279
                message = "Missing :action key on routes definition, please check your routes."
                raise ArgumentError, message
280
              end
J
Joshua Peek 已提交
281

282
              if controller.is_a?(String) && controller !~ /\A[a-z_0-9\/]*\z/
283 284 285 286 287
                message = "'#{controller}' is not a supported controller name. This can lead to potential routing problems."
                message << " See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use"
                raise ArgumentError, message
              end

A
Aaron Patterson 已提交
288
              hash = {}
A
Aaron Patterson 已提交
289 290
              hash[:controller] = controller unless controller.blank?
              hash[:action]     = action unless action.blank?
A
Aaron Patterson 已提交
291
              hash
292 293
            end
          end
294

295
          def blocks
296 297
            if options[:constraints].present? && !options[:constraints].is_a?(Hash)
              [options[:constraints]]
298
            else
299
              scope[:blocks] || []
300 301
            end
          end
J
Joshua Peek 已提交
302

303
          def constraints
304 305
            @constraints ||= {}.tap do |constraints|
              constraints.merge!(scope[:constraints]) if scope[:constraints]
306

307 308 309 310 311
              options.except(*IGNORE_OPTIONS).each do |key, option|
                constraints[key] = option if Regexp === option
              end

              constraints.merge!(options[:constraints]) if options[:constraints].is_a?(Hash)
312
            end
313
          end
J
Joshua Peek 已提交
314

315
          def segment_keys
316 317 318 319 320 321
            @segment_keys ||= path_pattern.names.map{ |s| s.to_sym }
          end

          def path_pattern
            Journey::Path::Pattern.new(strexp)
          end
322

323 324 325 326 327
          def strexp
            Journey::Router::Strexp.compile(path, requirements, SEPARATORS)
          end

          def dispatcher
328
            Routing::RouteSet::Dispatcher.new(defaults)
329 330
          end
      end
331

332
      # Invokes Journey::Router::Utils.normalize_path and ensure that
333 334
      # (:locale) becomes (/:locale) instead of /(:locale). Except
      # for root cases, where the latter is the correct one.
335
      def self.normalize_path(path)
336
        path = Journey::Router::Utils.normalize_path(path)
337
        path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$}
338 339 340
        path
      end

341
      def self.normalize_name(name)
342
        normalize_path(name)[1..-1].tr("/", "_")
343 344
      end

345
      module Base
346 347
        # You can specify what Rails should route "/" to with the root method:
        #
A
AvnerCohen 已提交
348
        #   root to: 'pages#main'
349
        #
350
        # For options, see +match+, as +root+ uses it internally.
351
        #
352 353 354 355
        # You can also pass a string which will expand
        #
        #   root 'pages#main'
        #
356 357 358
        # You should put the root route at the top of <tt>config/routes.rb</tt>,
        # because this means it will be matched first. As this is the most popular route
        # of most Rails applications, this is beneficial.
359
        def root(options = {})
360
          match '/', { :as => :root, :via => :get }.merge!(options)
361
        end
362

363
        # Matches a url pattern to one or more routes.
364
        #
365 366 367 368
        # You should not use the `match` method in your router
        # without specifying an HTTP method.
        #
        # If you want to expose your action to both GET and POST, use:
369
        #
370
        #   # sets :controller, :action and :id in params
371 372
        #   match ':controller/:action/:id', via: [:get, :post]
        #
373 374
        # Note that +:controller+, +:action+ and +:id+ are interpreted as url
        # query parameters and thus available through +params+ in an action.
375 376 377 378 379 380 381 382 383 384
        #
        # If you want to expose your action to GET, use `get` in the router:
        #
        # Instead of:
        #
        #   match ":controller/:action/:id"
        #
        # Do:
        #
        #   get ":controller/:action/:id"
385
        #
386 387 388 389
        # Two of these symbols are special, +:controller+ maps to the controller
        # and +:action+ to the controller's action. A pattern can also map
        # wildcard segments (globs) to params:
        #
390
        #   get 'songs/*category/:title', to: 'songs#show'
391 392 393 394 395
        #
        #   # 'songs/rock/classic/stairway-to-heaven' sets
        #   #  params[:category] = 'rock/classic'
        #   #  params[:title] = 'stairway-to-heaven'
        #
396 397 398 399
        # To match a wildcard parameter, it must have a name assigned to it.
        # Without a variable name to attach the glob parameter to, the route
        # can't be parsed.
        #
400 401
        # When a pattern points to an internal route, the route's +:action+ and
        # +:controller+ should be set in options or hash shorthand. Examples:
402
        #
403 404 405
        #   match 'photos/:id' => 'photos#show', via: :get
        #   match 'photos/:id', to: 'photos#show', via: :get
        #   match 'photos/:id', controller: 'photos', action: 'show', via: :get
406
        #
407 408 409
        # A pattern can also point to a +Rack+ endpoint i.e. anything that
        # responds to +call+:
        #
410 411
        #   match 'photos/:id', to: lambda {|hash| [200, {}, ["Coming soon"]] }, via: :get
        #   match 'photos/:id', to: PhotoRackApp, via: :get
412
        #   # Yes, controller actions are just rack endpoints
413
        #   match 'photos/:id', to: PhotosController.action(:show), via: :get
414
        #
415 416 417
        # Because requesting various HTTP verbs with a single action has security
        # implications, you must either specify the actions in
        # the via options or use one of the HtttpHelpers[rdoc-ref:HttpHelpers]
418
        # instead +match+
419
        #
420
        # === Options
421
        #
422
        # Any options not seen here are passed on as params with the url.
423 424 425 426 427 428 429 430 431 432 433 434 435
        #
        # [:controller]
        #   The route's controller.
        #
        # [:action]
        #   The route's action.
        #
        # [:path]
        #   The path prefix for the routes.
        #
        # [:module]
        #   The namespace for :controller.
        #
436
        #     match 'path', to: 'c#a', module: 'sekret', controller: 'posts', via: :get
437
        #     # => Sekret::PostsController
438 439 440 441 442 443 444 445 446
        #
        #   See <tt>Scoping#namespace</tt> for its scope equivalent.
        #
        # [:as]
        #   The name used to generate routing helpers.
        #
        # [:via]
        #   Allowed HTTP verb(s) for route.
        #
447 448 449
        #      match 'path', to: 'c#a', via: :get
        #      match 'path', to: 'c#a', via: [:get, :post]
        #      match 'path', to: 'c#a', via: :all
450 451
        #
        # [:to]
452 453
        #   Points to a +Rack+ endpoint. Can be an object that responds to
        #   +call+ or a string representing a controller's action.
454
        #
455 456 457
        #      match 'path', to: 'controller#action', via: :get
        #      match 'path', to: lambda { |env| [200, {}, ["Success!"]] }, via: :get
        #      match 'path', to: RackApp, via: :get
458 459 460
        #
        # [:on]
        #   Shorthand for wrapping routes in a specific RESTful context. Valid
461
        #   values are +:member+, +:collection+, and +:new+. Only use within
462 463 464
        #   <tt>resource(s)</tt> block. For example:
        #
        #      resource :bar do
465
        #        match 'foo', to: 'c#a', on: :member, via: [:get, :post]
466 467 468 469 470 471
        #      end
        #
        #   Is equivalent to:
        #
        #      resource :bar do
        #        member do
472
        #          match 'foo', to: 'c#a', via: [:get, :post]
473 474 475 476
        #        end
        #      end
        #
        # [:constraints]
Y
Yves Senn 已提交
477 478 479 480
        #   Constrains parameters with a hash of regular expressions
        #   or an object that responds to <tt>matches?</tt>. In addition, constraints
        #   other than path can also be specified with any object
        #   that responds to <tt>===</tt> (eg. String, Array, Range, etc.).
481
        #
482
        #     match 'path/:id', constraints: { id: /[A-Z]\d{5}/ }, via: :get
483
        #
484
        #     match 'json_only', constraints: { format: 'json' }, via: :get
Y
Yves Senn 已提交
485
        #
486
        #     class Whitelist
487 488
        #       def matches?(request) request.remote_ip == '1.2.3.4' end
        #     end
489
        #     match 'path', to: 'c#a', constraints: Whitelist.new, via: :get
490 491 492 493 494 495 496 497
        #
        #   See <tt>Scoping#constraints</tt> for more examples with its scope
        #   equivalent.
        #
        # [:defaults]
        #   Sets defaults for parameters
        #
        #     # Sets params[:format] to 'jpg' by default
498
        #     match 'path', to: 'c#a', defaults: { format: 'jpg' }, via: :get
499 500
        #
        #   See <tt>Scoping#defaults</tt> for its scope equivalent.
501 502
        #
        # [:anchor]
503
        #   Boolean to anchor a <tt>match</tt> pattern. Default is true. When set to
504 505 506
        #   false, the pattern matches any request prefixed with the given path.
        #
        #     # Matches any request starting with 'path'
507
        #     match 'path', to: 'c#a', anchor: false, via: :get
508 509
        #
        # [:format]
510
        #   Allows you to specify the default value for optional +format+
V
Vijay Dev 已提交
511
        #   segment or disable it by supplying +false+.
512
        def match(path, options=nil)
513
        end
514

515 516
        # Mount a Rack-based application to be used within the application.
        #
A
AvnerCohen 已提交
517
        #   mount SomeRackApp, at: "some_route"
518 519 520
        #
        # Alternatively:
        #
R
Ryan Bigg 已提交
521
        #   mount(SomeRackApp => "some_route")
522
        #
523 524
        # For options, see +match+, as +mount+ uses it internally.
        #
525 526 527 528 529
        # All mounted applications come with routing helpers to access them.
        # These are named after the class specified, so for the above example
        # the helper is either +some_rack_app_path+ or +some_rack_app_url+.
        # To customize this helper's name, use the +:as+ option:
        #
A
AvnerCohen 已提交
530
        #   mount(SomeRackApp => "some_route", as: "exciting")
531 532 533
        #
        # This will generate the +exciting_path+ and +exciting_url+ helpers
        # which can be used to navigate to this mounted app.
534 535 536 537
        def mount(app, options = nil)
          if options
            path = options.delete(:at)
          else
538 539 540 541
            unless Hash === app
              raise ArgumentError, "must be called with mount point"
            end

542
            options = app
543
            app, path = options.find { |k, _| k.respond_to?(:call) }
544 545 546 547 548
            options.delete(app) if app
          end

          raise "A rack application must be specified" unless path

P
Pratik Naik 已提交
549
          options[:as]  ||= app_name(app)
550
          target_as       = name_for_action(options[:as], path)
P
Pratik Naik 已提交
551
          options[:via] ||= :all
552

P
Pratik Naik 已提交
553
          match(path, options.merge(:to => app, :anchor => false, :format => false))
554

555
          define_generate_prefix(app, target_as)
556 557 558
          self
        end

559 560 561 562
        def default_url_options=(options)
          @set.default_url_options = options
        end
        alias_method :default_url_options, :default_url_options=
563

564 565 566 567 568 569
        def with_default_scope(scope, &block)
          scope(scope) do
            instance_exec(&block)
          end
        end

570 571 572 573 574
        # Query if the following named route was already defined.
        def has_named_route?(name)
          @set.named_routes.routes[name.to_sym]
        end

575 576 577
        private
          def app_name(app)
            return unless app.respond_to?(:routes)
578 579 580 581 582

            if app.respond_to?(:railtie_name)
              app.railtie_name
            else
              class_name = app.class.is_a?(Class) ? app.name : app.class.name
583
              ActiveSupport::Inflector.underscore(class_name).tr("/", "_")
584
            end
585 586 587
          end

          def define_generate_prefix(app, name)
588
            return unless app.respond_to?(:routes) && app.routes.respond_to?(:define_mounted_helper)
589 590

            _route = @set.named_routes.routes[name.to_sym]
P
Piotr Sarnacki 已提交
591 592
            _routes = @set
            app.routes.define_mounted_helper(name)
593 594
            app.routes.extend Module.new {
              def mounted?; true; end
595 596
              define_method :find_script_name do |options|
                super(options) || begin
P
Piotr Sarnacki 已提交
597
                prefix_options = options.slice(*_route.segment_keys)
598 599
                # we must actually delete prefix segment keys to avoid passing them to next url_for
                _route.segment_keys.each { |k| options.delete(k) }
600
                _routes.url_helpers.send("#{name}_path", prefix_options)
601
                end
602
              end
603
            }
604
          end
605 606 607
      end

      module HttpHelpers
608
        # Define a route that only recognizes HTTP GET.
C
Cesar Carruitero 已提交
609
        # For supported arguments, see match[rdoc-ref:Base#match]
610
        #
A
AvnerCohen 已提交
611
        #   get 'bacon', to: 'food#bacon'
612
        def get(*args, &block)
613
          map_method(:get, args, &block)
614 615
        end

616
        # Define a route that only recognizes HTTP POST.
C
Cesar Carruitero 已提交
617
        # For supported arguments, see match[rdoc-ref:Base#match]
618
        #
A
AvnerCohen 已提交
619
        #   post 'bacon', to: 'food#bacon'
620
        def post(*args, &block)
621
          map_method(:post, args, &block)
622 623
        end

624
        # Define a route that only recognizes HTTP PATCH.
C
Cesar Carruitero 已提交
625
        # For supported arguments, see match[rdoc-ref:Base#match]
626
        #
A
AvnerCohen 已提交
627
        #   patch 'bacon', to: 'food#bacon'
628 629 630 631
        def patch(*args, &block)
          map_method(:patch, args, &block)
        end

632
        # Define a route that only recognizes HTTP PUT.
C
Cesar Carruitero 已提交
633
        # For supported arguments, see match[rdoc-ref:Base#match]
634
        #
A
AvnerCohen 已提交
635
        #   put 'bacon', to: 'food#bacon'
636
        def put(*args, &block)
637
          map_method(:put, args, &block)
638 639
        end

640
        # Define a route that only recognizes HTTP DELETE.
C
Cesar Carruitero 已提交
641
        # For supported arguments, see match[rdoc-ref:Base#match]
642
        #
A
AvnerCohen 已提交
643
        #   delete 'broccoli', to: 'food#broccoli'
644
        def delete(*args, &block)
645
          map_method(:delete, args, &block)
646 647 648
        end

        private
649
          def map_method(method, args, &block)
650
            options = args.extract_options!
651
            options[:via] = method
652
            match(*args, options, &block)
653 654 655 656
            self
          end
      end

657 658 659
      # You may wish to organize groups of controllers under a namespace.
      # Most commonly, you might group a number of administrative controllers
      # under an +admin+ namespace. You would place these controllers under
S
Sebastian Martinez 已提交
660 661
      # the <tt>app/controllers/admin</tt> directory, and you can group them
      # together in your router:
662 663 664 665
      #
      #   namespace "admin" do
      #     resources :posts, :comments
      #   end
666
      #
667
      # This will create a number of routes for each of the posts and comments
S
Sebastian Martinez 已提交
668
      # controller. For <tt>Admin::PostsController</tt>, Rails will create:
669
      #
670 671 672 673 674
      #   GET       /admin/posts
      #   GET       /admin/posts/new
      #   POST      /admin/posts
      #   GET       /admin/posts/1
      #   GET       /admin/posts/1/edit
675
      #   PATCH/PUT /admin/posts/1
676
      #   DELETE    /admin/posts/1
677
      #
678
      # If you want to route /posts (without the prefix /admin) to
S
Sebastian Martinez 已提交
679
      # <tt>Admin::PostsController</tt>, you could use
680
      #
A
AvnerCohen 已提交
681
      #   scope module: "admin" do
682
      #     resources :posts
683 684 685
      #   end
      #
      # or, for a single case
686
      #
A
AvnerCohen 已提交
687
      #   resources :posts, module: "admin"
688
      #
S
Sebastian Martinez 已提交
689
      # If you want to route /admin/posts to +PostsController+
690
      # (without the Admin:: module prefix), you could use
691
      #
692
      #   scope "/admin" do
693
      #     resources :posts
694 695 696
      #   end
      #
      # or, for a single case
697
      #
A
AvnerCohen 已提交
698
      #   resources :posts, path: "/admin/posts"
699 700 701
      #
      # In each of these cases, the named routes remain the same as if you did
      # not use scope. In the last case, the following paths map to
S
Sebastian Martinez 已提交
702
      # +PostsController+:
703
      #
704 705 706 707 708
      #   GET       /admin/posts
      #   GET       /admin/posts/new
      #   POST      /admin/posts
      #   GET       /admin/posts/1
      #   GET       /admin/posts/1/edit
709
      #   PATCH/PUT /admin/posts/1
710
      #   DELETE    /admin/posts/1
711
      module Scoping
712
        # Scopes a set of routes to the given default options.
713 714 715
        #
        # Take the following route definition as an example:
        #
A
AvnerCohen 已提交
716
        #   scope path: ":account_id", as: "account" do
717 718 719 720
        #     resources :projects
        #   end
        #
        # This generates helpers such as +account_projects_path+, just like +resources+ does.
721 722
        # The difference here being that the routes generated are like /:account_id/projects,
        # rather than /accounts/:account_id/projects.
723
        #
724
        # === Options
725
        #
726
        # Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>.
727
        #
S
Sebastian Martinez 已提交
728
        #   # route /posts (without the prefix /admin) to <tt>Admin::PostsController</tt>
A
AvnerCohen 已提交
729
        #   scope module: "admin" do
730 731
        #     resources :posts
        #   end
732
        #
733
        #   # prefix the posts resource's requests with '/admin'
A
AvnerCohen 已提交
734
        #   scope path: "/admin" do
735 736
        #     resources :posts
        #   end
737
        #
S
Sebastian Martinez 已提交
738
        #   # prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+
A
AvnerCohen 已提交
739
        #   scope as: "sekret" do
740 741
        #     resources :posts
        #   end
742
        def scope(*args)
743
          options = args.extract_options!.dup
744
          recover = {}
745

746
          options[:path] = args.flatten.join('/') if args.any?
747
          options[:constraints] ||= {}
748

749
          unless nested_scope?
750 751
            options[:shallow_path] ||= options[:path] if options.key?(:path)
            options[:shallow_prefix] ||= options[:as] if options.key?(:as)
752 753
          end

754
          if options[:constraints].is_a?(Hash)
755 756 757 758 759
            defaults = options[:constraints].select do
              |k, v| URL_OPTIONS.include?(k) && (v.is_a?(String) || v.is_a?(Fixnum))
            end

            (options[:defaults] ||= {}).reverse_merge!(defaults)
760 761
          else
            block, options[:constraints] = options[:constraints], {}
762 763
          end

764 765 766 767 768 769 770 771 772 773
          SCOPE_OPTIONS.each do |option|
            if option == :blocks
              value = block
            elsif option == :options
              value = options
            else
              value = options.delete(option)
            end

            if value
774 775 776
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
777 778 779 780 781
          end

          yield
          self
        ensure
782
          @scope.merge!(recover)
783 784
        end

785 786 787
        # Scopes routes to a specific controller
        #
        #   controller "food" do
A
AvnerCohen 已提交
788
        #     match "bacon", action: "bacon"
789
        #   end
790 791 792
        def controller(controller, options={})
          options[:controller] = controller
          scope(options) { yield }
793 794
        end

795 796 797 798 799 800 801 802
        # Scopes routes to a specific namespace. For example:
        #
        #   namespace :admin do
        #     resources :posts
        #   end
        #
        # This generates the following routes:
        #
803 804 805 806 807
        #       admin_posts GET       /admin/posts(.:format)          admin/posts#index
        #       admin_posts POST      /admin/posts(.:format)          admin/posts#create
        #    new_admin_post GET       /admin/posts/new(.:format)      admin/posts#new
        #   edit_admin_post GET       /admin/posts/:id/edit(.:format) admin/posts#edit
        #        admin_post GET       /admin/posts/:id(.:format)      admin/posts#show
808
        #        admin_post PATCH/PUT /admin/posts/:id(.:format)      admin/posts#update
809
        #        admin_post DELETE    /admin/posts/:id(.:format)      admin/posts#destroy
810
        #
811
        # === Options
812
        #
813 814
        # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
        # options all default to the name of the namespace.
815
        #
816 817
        # For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
        # <tt>Resources#resources</tt>.
818
        #
819
        #   # accessible through /sekret/posts rather than /admin/posts
A
AvnerCohen 已提交
820
        #   namespace :admin, path: "sekret" do
821 822
        #     resources :posts
        #   end
823
        #
S
Sebastian Martinez 已提交
824
        #   # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
A
AvnerCohen 已提交
825
        #   namespace :admin, module: "sekret" do
826 827
        #     resources :posts
        #   end
828
        #
S
Sebastian Martinez 已提交
829
        #   # generates +sekret_posts_path+ rather than +admin_posts_path+
A
AvnerCohen 已提交
830
        #   namespace :admin, as: "sekret" do
831 832
        #     resources :posts
        #   end
833
        def namespace(path, options = {})
834
          path = path.to_s
835 836 837 838 839 840 841 842 843 844

          defaults = {
            module:         path,
            path:           options.fetch(:path, path),
            as:             options.fetch(:as, path),
            shallow_path:   options.fetch(:path, path),
            shallow_prefix: options.fetch(:as, path)
          }

          scope(defaults.merge!(options)) { yield }
845
        end
846

R
Ryan Bigg 已提交
847 848 849 850
        # === Parameter Restriction
        # Allows you to constrain the nested routes based on a set of rules.
        # For instance, in order to change the routes to allow for a dot character in the +id+ parameter:
        #
A
AvnerCohen 已提交
851
        #   constraints(id: /\d+\.\d+/) do
R
Ryan Bigg 已提交
852 853 854 855 856
        #     resources :posts
        #   end
        #
        # Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be.
        # The +id+ parameter must match the constraint passed in for this example.
857
        #
R
R.T. Lechow 已提交
858
        # You may use this to also restrict other parameters:
R
Ryan Bigg 已提交
859 860
        #
        #   resources :posts do
A
AvnerCohen 已提交
861
        #     constraints(post_id: /\d+\.\d+/) do
R
Ryan Bigg 已提交
862 863
        #       resources :comments
        #     end
J
James Miller 已提交
864
        #   end
R
Ryan Bigg 已提交
865 866 867 868 869
        #
        # === Restricting based on IP
        #
        # Routes can also be constrained to an IP or a certain range of IP addresses:
        #
A
AvnerCohen 已提交
870
        #   constraints(ip: /192\.168\.\d+\.\d+/) do
R
Ryan Bigg 已提交
871 872 873 874 875 876 877 878
        #     resources :posts
        #   end
        #
        # Any user connecting from the 192.168.* range will be able to see this resource,
        # where as any user connecting outside of this range will be told there is no such route.
        #
        # === Dynamic request matching
        #
R
R.T. Lechow 已提交
879
        # Requests to routes can be constrained based on specific criteria:
R
Ryan Bigg 已提交
880 881 882 883 884 885 886 887 888 889
        #
        #    constraints(lambda { |req| req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do
        #      resources :iphones
        #    end
        #
        # You are able to move this logic out into a class if it is too complex for routes.
        # This class must have a +matches?+ method defined on it which either returns +true+
        # if the user should be given access to that route, or +false+ if the user should not.
        #
        #    class Iphone
890
        #      def self.matches?(request)
R
Ryan Bigg 已提交
891 892 893 894 895 896 897 898 899 900 901
        #        request.env["HTTP_USER_AGENT"] =~ /iPhone/
        #      end
        #    end
        #
        # An expected place for this code would be +lib/constraints+.
        #
        # This class is then used like this:
        #
        #    constraints(Iphone) do
        #      resources :iphones
        #    end
902 903 904 905
        def constraints(constraints = {})
          scope(:constraints => constraints) { yield }
        end

R
Ryan Bigg 已提交
906
        # Allows you to set default parameters for a route, such as this:
A
AvnerCohen 已提交
907 908
        #   defaults id: 'home' do
        #     match 'scoped_pages/(:id)', to: 'pages#show'
909
        #   end
R
Ryan Bigg 已提交
910
        # Using this, the +:id+ parameter here will default to 'home'.
911 912 913 914
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

915
        private
J
José Valim 已提交
916
          def merge_path_scope(parent, child) #:nodoc:
917
            Mapper.normalize_path("#{parent}/#{child}")
918 919
          end

J
José Valim 已提交
920
          def merge_shallow_path_scope(parent, child) #:nodoc:
921 922 923
            Mapper.normalize_path("#{parent}/#{child}")
          end

J
José Valim 已提交
924
          def merge_as_scope(parent, child) #:nodoc:
925
            parent ? "#{parent}_#{child}" : child
926 927
          end

J
José Valim 已提交
928
          def merge_shallow_prefix_scope(parent, child) #:nodoc:
929 930 931
            parent ? "#{parent}_#{child}" : child
          end

J
José Valim 已提交
932
          def merge_module_scope(parent, child) #:nodoc:
933 934 935
            parent ? "#{parent}/#{child}" : child
          end

J
José Valim 已提交
936
          def merge_controller_scope(parent, child) #:nodoc:
937
            child
938 939
          end

940 941 942 943
          def merge_action_scope(parent, child) #:nodoc:
            child
          end

J
José Valim 已提交
944
          def merge_path_names_scope(parent, child) #:nodoc:
945 946 947
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
948
          def merge_constraints_scope(parent, child) #:nodoc:
949 950 951
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
952
          def merge_defaults_scope(parent, child) #:nodoc:
953 954 955
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
956
          def merge_blocks_scope(parent, child) #:nodoc:
957 958 959
            merged = parent ? parent.dup : []
            merged << child if child
            merged
960 961
          end

J
José Valim 已提交
962
          def merge_options_scope(parent, child) #:nodoc:
963
            (parent || {}).except(*override_keys(child)).merge!(child)
964
          end
965

J
José Valim 已提交
966
          def merge_shallow_scope(parent, child) #:nodoc:
967 968
            child ? true : false
          end
969

J
José Valim 已提交
970
          def override_keys(child) #:nodoc:
971 972
            child.key?(:only) || child.key?(:except) ? [:only, :except] : []
          end
973 974
      end

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
      # Resource routing allows you to quickly declare all of the common routes
      # for a given resourceful controller. Instead of declaring separate routes
      # for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+
      # actions, a resourceful route declares them in a single line of code:
      #
      #  resources :photos
      #
      # Sometimes, you have a resource that clients always look up without
      # referencing an ID. A common example, /profile always shows the profile of
      # the currently logged in user. In this case, you can use a singular resource
      # to map /profile (rather than /profile/:id) to the show action.
      #
      #  resource :profile
      #
      # It's common to have resources that are logically children of other
      # resources:
      #
      #   resources :magazines do
      #     resources :ads
      #   end
      #
      # You may wish to organize groups of controllers under a namespace. Most
      # commonly, you might group a number of administrative controllers under
      # an +admin+ namespace. You would place these controllers under the
S
Sebastian Martinez 已提交
999 1000
      # <tt>app/controllers/admin</tt> directory, and you can group them together
      # in your router:
1001 1002 1003 1004 1005
      #
      #   namespace "admin" do
      #     resources :posts, :comments
      #   end
      #
S
Sebastian Martinez 已提交
1006 1007
      # By default the +:id+ parameter doesn't accept dots. If you need to
      # use dots as part of the +:id+ parameter add a constraint which
1008 1009
      # overrides this restriction, e.g:
      #
A
AvnerCohen 已提交
1010
      #   resources :articles, id: /[^\/]+/
1011
      #
S
Sebastian Martinez 已提交
1012
      # This allows any character other than a slash as part of your +:id+.
1013
      #
J
Joshua Peek 已提交
1014
      module Resources
1015 1016
        # CANONICAL_ACTIONS holds all actions that does not need a prefix or
        # a path appended since they fit properly in their scope level.
1017
        VALID_ON_OPTIONS  = [:new, :collection, :member]
1018
        RESOURCE_OPTIONS  = [:as, :controller, :path, :only, :except, :param, :concerns]
1019
        CANONICAL_ACTIONS = %w(index create new show update destroy)
1020 1021
        RESOURCE_METHOD_SCOPES = [:collection, :member, :new]
        RESOURCE_SCOPES = [:resource, :resources]
1022

1023
        class Resource #:nodoc:
1024
          attr_reader :controller, :path, :options, :param
1025 1026

          def initialize(entities, options = {})
1027
            @name       = entities.to_s
1028 1029 1030
            @path       = (options[:path] || @name).to_s
            @controller = (options[:controller] || @name).to_s
            @as         = options[:as]
1031
            @param      = (options[:param] || :id).to_sym
1032
            @options    = options
1033
            @shallow    = false
1034 1035
          end

1036
          def default_actions
1037
            [:index, :create, :new, :show, :update, :destroy, :edit]
1038 1039
          end

1040
          def actions
1041
            if only = @options[:only]
1042
              Array(only).map(&:to_sym)
1043
            elsif except = @options[:except]
1044 1045 1046 1047 1048 1049
              default_actions - Array(except).map(&:to_sym)
            else
              default_actions
            end
          end

1050
          def name
1051
            @as || @name
1052 1053
          end

1054
          def plural
1055
            @plural ||= name.to_s
1056 1057 1058
          end

          def singular
1059
            @singular ||= name.to_s.singularize
1060 1061
          end

1062
          alias :member_name :singular
1063

1064
          # Checks for uncountable plurals, and appends "_index" if the plural
1065
          # and singular form are the same.
1066
          def collection_name
1067
            singular == plural ? "#{plural}_index" : plural
1068 1069
          end

1070
          def resource_scope
1071
            { :controller => controller }
1072 1073
          end

1074
          alias :collection_scope :path
1075 1076

          def member_scope
1077
            "#{path}/:#{param}"
1078 1079
          end

1080 1081
          alias :shallow_scope :member_scope

1082
          def new_scope(new_path)
1083
            "#{path}/#{new_path}"
1084 1085
          end

1086 1087 1088 1089
          def nested_param
            :"#{singular}_#{param}"
          end

1090
          def nested_scope
1091
            "#{path}/:#{nested_param}"
1092
          end
1093

1094 1095 1096 1097 1098 1099 1100
          def shallow=(value)
            @shallow = value
          end

          def shallow?
            @shallow
          end
1101 1102 1103
        end

        class SingletonResource < Resource #:nodoc:
1104
          def initialize(entities, options)
1105
            super
1106
            @as         = nil
1107 1108
            @controller = (options[:controller] || plural).to_s
            @as         = options[:as]
1109 1110
          end

1111 1112 1113 1114
          def default_actions
            [:show, :create, :update, :destroy, :new, :edit]
          end

1115 1116
          def plural
            @plural ||= name.to_s.pluralize
1117 1118
          end

1119 1120
          def singular
            @singular ||= name.to_s
1121
          end
1122 1123 1124 1125 1126 1127

          alias :member_name :singular
          alias :collection_name :singular

          alias :member_scope :path
          alias :nested_scope :path
1128 1129
        end

1130 1131 1132 1133
        def resources_path_names(options)
          @scope[:path_names].merge!(options)
        end

1134 1135 1136 1137 1138 1139
        # Sometimes, you have a resource that clients always look up without
        # referencing an ID. A common example, /profile always shows the
        # profile of the currently logged in user. In this case, you can use
        # a singular resource to map /profile (rather than /profile/:id) to
        # the show action:
        #
1140
        #   resource :profile
1141 1142
        #
        # creates six different routes in your application, all mapping to
1143
        # the +Profiles+ controller (note that the controller is named after
1144 1145
        # the plural):
        #
1146 1147 1148 1149 1150 1151
        #   GET       /profile/new
        #   POST      /profile
        #   GET       /profile
        #   GET       /profile/edit
        #   PATCH/PUT /profile
        #   DELETE    /profile
1152
        #
1153
        # === Options
1154
        # Takes same options as +resources+.
J
Joshua Peek 已提交
1155
        def resource(*resources, &block)
1156
          options = resources.extract_options!.dup
J
Joshua Peek 已提交
1157

1158
          if apply_common_behavior_for(:resource, resources, options, &block)
1159 1160 1161
            return self
          end

1162
          resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
1163
            yield if block_given?
1164

1165 1166
            concerns(options[:concerns]) if options[:concerns]

1167
            collection do
1168
              post :create
1169
            end if parent_resource.actions.include?(:create)
1170

1171
            new do
1172
              get :new
1173
            end if parent_resource.actions.include?(:new)
1174

1175
            set_member_mappings_for_resource
1176 1177
          end

J
Joshua Peek 已提交
1178
          self
1179 1180
        end

1181 1182 1183 1184 1185 1186 1187 1188
        # In Rails, a resourceful route provides a mapping between HTTP verbs
        # and URLs and controller actions. By convention, each action also maps
        # to particular CRUD operations in a database. A single entry in the
        # routing file, such as
        #
        #   resources :photos
        #
        # creates seven different routes in your application, all mapping to
S
Sebastian Martinez 已提交
1189
        # the +Photos+ controller:
1190
        #
1191 1192 1193 1194 1195
        #   GET       /photos
        #   GET       /photos/new
        #   POST      /photos
        #   GET       /photos/:id
        #   GET       /photos/:id/edit
1196
        #   PATCH/PUT /photos/:id
1197
        #   DELETE    /photos/:id
1198
        #
1199 1200 1201 1202 1203 1204 1205 1206
        # Resources can also be nested infinitely by using this block syntax:
        #
        #   resources :photos do
        #     resources :comments
        #   end
        #
        # This generates the following comments routes:
        #
1207 1208 1209 1210 1211
        #   GET       /photos/:photo_id/comments
        #   GET       /photos/:photo_id/comments/new
        #   POST      /photos/:photo_id/comments
        #   GET       /photos/:photo_id/comments/:id
        #   GET       /photos/:photo_id/comments/:id/edit
1212
        #   PATCH/PUT /photos/:photo_id/comments/:id
1213
        #   DELETE    /photos/:photo_id/comments/:id
1214
        #
1215
        # === Options
1216 1217
        # Takes same options as <tt>Base#match</tt> as well as:
        #
1218
        # [:path_names]
A
Aviv Ben-Yosef 已提交
1219 1220
        #   Allows you to change the segment component of the +edit+ and +new+ actions.
        #   Actions not specified are not changed.
1221
        #
A
AvnerCohen 已提交
1222
        #     resources :posts, path_names: { new: "brand_new" }
1223 1224
        #
        #   The above example will now change /posts/new to /posts/brand_new
1225
        #
1226 1227 1228
        # [:path]
        #   Allows you to change the path prefix for the resource.
        #
A
AvnerCohen 已提交
1229
        #     resources :posts, path: 'postings'
1230 1231 1232
        #
        #   The resource and all segments will now route to /postings instead of /posts
        #
1233 1234
        # [:only]
        #   Only generate routes for the given actions.
1235
        #
A
AvnerCohen 已提交
1236 1237
        #     resources :cows, only: :show
        #     resources :cows, only: [:show, :index]
1238
        #
1239 1240
        # [:except]
        #   Generate all routes except for the given actions.
1241
        #
A
AvnerCohen 已提交
1242 1243
        #     resources :cows, except: :show
        #     resources :cows, except: [:show, :index]
1244 1245 1246 1247 1248
        #
        # [:shallow]
        #   Generates shallow routes for nested resource(s). When placed on a parent resource,
        #   generates shallow routes for all nested resources.
        #
A
AvnerCohen 已提交
1249
        #     resources :posts, shallow: true do
1250 1251 1252 1253 1254 1255
        #       resources :comments
        #     end
        #
        #   Is the same as:
        #
        #     resources :posts do
A
AvnerCohen 已提交
1256
        #       resources :comments, except: [:show, :edit, :update, :destroy]
1257
        #     end
A
AvnerCohen 已提交
1258
        #     resources :comments, only: [:show, :edit, :update, :destroy]
1259 1260 1261 1262
        #
        #   This allows URLs for resources that otherwise would be deeply nested such
        #   as a comment on a blog post like <tt>/posts/a-long-permalink/comments/1234</tt>
        #   to be shortened to just <tt>/comments/1234</tt>.
1263 1264 1265 1266
        #
        # [:shallow_path]
        #   Prefixes nested shallow routes with the specified path.
        #
A
AvnerCohen 已提交
1267
        #     scope shallow_path: "sekret" do
1268
        #       resources :posts do
A
AvnerCohen 已提交
1269
        #         resources :comments, shallow: true
1270
        #       end
1271 1272 1273 1274
        #     end
        #
        #   The +comments+ resource here will have the following routes generated for it:
        #
1275 1276 1277 1278 1279
        #     post_comments    GET       /posts/:post_id/comments(.:format)
        #     post_comments    POST      /posts/:post_id/comments(.:format)
        #     new_post_comment GET       /posts/:post_id/comments/new(.:format)
        #     edit_comment     GET       /sekret/comments/:id/edit(.:format)
        #     comment          GET       /sekret/comments/:id(.:format)
1280
        #     comment          PATCH/PUT /sekret/comments/:id(.:format)
1281
        #     comment          DELETE    /sekret/comments/:id(.:format)
1282
        #
1283 1284 1285
        # [:shallow_prefix]
        #   Prefixes nested shallow route names with specified prefix.
        #
A
AvnerCohen 已提交
1286
        #     scope shallow_prefix: "sekret" do
1287
        #       resources :posts do
A
AvnerCohen 已提交
1288
        #         resources :comments, shallow: true
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
        #       end
        #     end
        #
        #   The +comments+ resource here will have the following routes generated for it:
        #
        #     post_comments           GET       /posts/:post_id/comments(.:format)
        #     post_comments           POST      /posts/:post_id/comments(.:format)
        #     new_post_comment        GET       /posts/:post_id/comments/new(.:format)
        #     edit_sekret_comment     GET       /comments/:id/edit(.:format)
        #     sekret_comment          GET       /comments/:id(.:format)
        #     sekret_comment          PATCH/PUT /comments/:id(.:format)
        #     sekret_comment          DELETE    /comments/:id(.:format)
        #
1302
        # [:format]
1303
        #   Allows you to specify the default value for optional +format+
V
Vijay Dev 已提交
1304
        #   segment or disable it by supplying +false+.
1305
        #
1306
        # === Examples
1307
        #
S
Sebastian Martinez 已提交
1308
        #   # routes call <tt>Admin::PostsController</tt>
A
AvnerCohen 已提交
1309
        #   resources :posts, module: "admin"
1310
        #
1311
        #   # resource actions are at /admin/posts.
A
AvnerCohen 已提交
1312
        #   resources :posts, path: "admin/posts"
J
Joshua Peek 已提交
1313
        def resources(*resources, &block)
1314
          options = resources.extract_options!.dup
1315

1316
          if apply_common_behavior_for(:resources, resources, options, &block)
1317 1318 1319
            return self
          end

1320
          resource_scope(:resources, Resource.new(resources.pop, options)) do
1321
            yield if block_given?
J
Joshua Peek 已提交
1322

1323 1324
            concerns(options[:concerns]) if options[:concerns]

1325
            collection do
1326 1327
              get  :index if parent_resource.actions.include?(:index)
              post :create if parent_resource.actions.include?(:create)
1328
            end
1329

1330
            new do
1331
              get :new
1332
            end if parent_resource.actions.include?(:new)
1333

1334
            set_member_mappings_for_resource
1335 1336
          end

J
Joshua Peek 已提交
1337
          self
1338 1339
        end

1340 1341 1342 1343 1344 1345 1346 1347 1348
        # To add a route to the collection:
        #
        #   resources :photos do
        #     collection do
        #       get 'search'
        #     end
        #   end
        #
        # This will enable Rails to recognize paths such as <tt>/photos/search</tt>
S
Sebastian Martinez 已提交
1349
        # with GET, and route to the search action of +PhotosController+. It will also
1350 1351
        # create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
        # route helpers.
J
Joshua Peek 已提交
1352
        def collection
1353 1354
          unless resource_scope?
            raise ArgumentError, "can't use collection outside resource(s) scope"
1355 1356
          end

1357 1358 1359 1360
          with_scope_level(:collection) do
            scope(parent_resource.collection_scope) do
              yield
            end
J
Joshua Peek 已提交
1361
          end
1362
        end
J
Joshua Peek 已提交
1363

1364 1365 1366 1367 1368 1369 1370 1371 1372
        # To add a member route, add a member block into the resource block:
        #
        #   resources :photos do
        #     member do
        #       get 'preview'
        #     end
        #   end
        #
        # This will recognize <tt>/photos/1/preview</tt> with GET, and route to the
S
Sebastian Martinez 已提交
1373
        # preview action of +PhotosController+. It will also create the
1374
        # <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
J
Joshua Peek 已提交
1375
        def member
1376 1377
          unless resource_scope?
            raise ArgumentError, "can't use member outside resource(s) scope"
J
Joshua Peek 已提交
1378
          end
J
Joshua Peek 已提交
1379

1380
          with_scope_level(:member) do
1381 1382 1383 1384
            if shallow?
              shallow_scope(parent_resource.member_scope) { yield }
            else
              scope(parent_resource.member_scope) { yield }
1385
            end
1386 1387 1388 1389 1390 1391 1392
          end
        end

        def new
          unless resource_scope?
            raise ArgumentError, "can't use new outside resource(s) scope"
          end
1393

1394 1395 1396 1397
          with_scope_level(:new) do
            scope(parent_resource.new_scope(action_path(:new))) do
              yield
            end
J
Joshua Peek 已提交
1398
          end
J
Joshua Peek 已提交
1399 1400
        end

1401
        def nested
1402 1403
          unless resource_scope?
            raise ArgumentError, "can't use nested outside resource(s) scope"
1404 1405 1406
          end

          with_scope_level(:nested) do
1407
            if shallow? && shallow_nesting_depth > 1
1408
              shallow_scope(parent_resource.nested_scope, nested_options) { yield }
1409
            else
1410
              scope(parent_resource.nested_scope, nested_options) { yield }
1411 1412 1413 1414
            end
          end
        end

1415
        # See ActionDispatch::Routing::Mapper::Scoping#namespace
1416
        def namespace(path, options = {})
1417
          if resource_scope?
1418 1419 1420 1421 1422 1423
            nested { super }
          else
            super
          end
        end

1424
        def shallow
1425
          scope(:shallow => true) do
1426 1427 1428 1429
            yield
          end
        end

1430 1431 1432 1433
        def shallow?
          parent_resource.instance_of?(Resource) && @scope[:shallow]
        end

1434
        # match 'path' => 'controller#action'
R
Rafael Mendonça França 已提交
1435
        # match 'path', to: 'controller#action'
1436
        # match 'path', 'otherpath', on: :member, via: :get
1437 1438 1439
        def match(path, *rest)
          if rest.empty? && Hash === path
            options  = path
1440
            path, to = options.find { |name, _value| name.is_a?(String) }
1441 1442
            options[:to] = to
            options.delete(path)
1443 1444 1445 1446 1447 1448
            paths = [path]
          else
            options = rest.pop || {}
            paths = [path] + rest
          end

1449 1450
          options[:anchor] = true unless options.key?(:anchor)

A
Aaron Patterson 已提交
1451 1452 1453 1454
          if options[:on] && !VALID_ON_OPTIONS.include?(options[:on])
            raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
          end

1455 1456 1457 1458
          if @scope[:controller] && @scope[:action]
            options[:to] ||= "#{@scope[:controller]}##{@scope[:action]}"
          end

1459 1460 1461
          paths.each do |_path|
            route_options = options.dup
            route_options[:path] ||= _path if _path.is_a?(String)
1462 1463 1464 1465

            path_without_format = _path.to_s.sub(/\(\.:format\)$/, '')
            if using_match_shorthand?(path_without_format, route_options)
              route_options[:to] ||= path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1')
1466
              route_options[:to].tr!("-", "_")
1467 1468
            end

1469 1470
            decomposed_match(_path, route_options)
          end
1471 1472
          self
        end
1473

1474 1475 1476 1477
        def using_match_shorthand?(path, options)
          path && (options[:to] || options[:action]).nil? && path =~ %r{/[\w/]+$}
        end

1478
        def decomposed_match(path, options) # :nodoc:
A
Aaron Patterson 已提交
1479 1480
          if on = options.delete(:on)
            send(on) { decomposed_match(path, options) }
1481
          else
A
Aaron Patterson 已提交
1482 1483 1484 1485 1486 1487 1488 1489
            case @scope[:scope_level]
            when :resources
              nested { decomposed_match(path, options) }
            when :resource
              member { decomposed_match(path, options) }
            else
              add_route(path, options)
            end
J
Joshua Peek 已提交
1490
          end
1491
        end
J
Joshua Peek 已提交
1492

1493
        def add_route(action, options) # :nodoc:
1494
          path = path_for_action(action, options.delete(:path))
1495
          action = action.to_s.dup
1496

1497
          if action =~ /^[\w\-\/]+$/
1498
            options[:action] ||= action.tr('-', '_') unless action.include?("/")
1499
          else
1500 1501 1502
            action = nil
          end

1503
          if !options.fetch(:as, true)
1504 1505 1506
            options.delete(:as)
          else
            options[:as] = name_for_action(options[:as], action)
J
Joshua Peek 已提交
1507
          end
J
Joshua Peek 已提交
1508

1509
          mapping = Mapping.new(@set, @scope, URI.parser.escape(path), options)
1510 1511
          app, conditions, requirements, defaults, as, anchor = mapping.to_route
          @set.add_route(app, conditions, requirements, defaults, as, anchor)
J
Joshua Peek 已提交
1512 1513
        end

1514 1515 1516 1517 1518 1519 1520 1521 1522
        def root(path, options={})
          if path.is_a?(String)
            options[:to] = path
          elsif path.is_a?(Hash) and options.empty?
            options = path
          else
            raise ArgumentError, "must be called with a path and/or options"
          end

1523
          if @scope[:scope_level] == :resources
1524 1525
            with_scope_level(:root) do
              scope(parent_resource.path) do
1526 1527 1528 1529 1530 1531
                super(options)
              end
            end
          else
            super(options)
          end
1532 1533
        end

1534
        protected
1535

1536
          def parent_resource #:nodoc:
1537 1538 1539
            @scope[:scope_level_resource]
          end

J
José Valim 已提交
1540
          def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
1541 1542 1543 1544 1545
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

1546 1547 1548 1549 1550 1551 1552
            if options.delete(:shallow)
              shallow do
                send(method, resources.pop, options, &block)
              end
              return true
            end

1553 1554 1555 1556 1557
            if resource_scope?
              nested { send(method, resources.pop, options, &block) }
              return true
            end

1558
            options.keys.each do |k|
1559 1560 1561
              (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
            end

1562 1563 1564
            scope_options = options.slice!(*RESOURCE_OPTIONS)
            unless scope_options.empty?
              scope(scope_options) do
1565 1566 1567 1568 1569
                send(method, resources.pop, options, &block)
              end
              return true
            end

1570 1571 1572 1573
            unless action_options?(options)
              options.merge!(scope_action_options) if scope_action_options?
            end

1574 1575 1576
            false
          end

J
José Valim 已提交
1577
          def action_options?(options) #:nodoc:
1578 1579 1580
            options[:only] || options[:except]
          end

J
José Valim 已提交
1581
          def scope_action_options? #:nodoc:
A
Aaron Patterson 已提交
1582
            @scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
1583 1584
          end

J
José Valim 已提交
1585
          def scope_action_options #:nodoc:
1586 1587 1588
            @scope[:options].slice(:only, :except)
          end

J
José Valim 已提交
1589
          def resource_scope? #:nodoc:
1590
            RESOURCE_SCOPES.include? @scope[:scope_level]
1591 1592
          end

J
José Valim 已提交
1593
          def resource_method_scope? #:nodoc:
1594
            RESOURCE_METHOD_SCOPES.include? @scope[:scope_level]
1595 1596
          end

1597 1598 1599 1600
          def nested_scope? #:nodoc:
            @scope[:scope_level] == :nested
          end

1601
          def with_exclusive_scope
1602
            begin
1603 1604
              old_name_prefix, old_path = @scope[:as], @scope[:path]
              @scope[:as], @scope[:path] = nil, nil
1605

1606 1607 1608
              with_scope_level(:exclusive) do
                yield
              end
1609
            ensure
1610
              @scope[:as], @scope[:path] = old_name_prefix, old_path
1611 1612 1613
            end
          end

1614
          def with_scope_level(kind)
J
Joshua Peek 已提交
1615 1616 1617 1618 1619
            old, @scope[:scope_level] = @scope[:scope_level], kind
            yield
          ensure
            @scope[:scope_level] = old
          end
1620

1621
          def resource_scope(kind, resource) #:nodoc:
1622
            resource.shallow = @scope[:shallow]
1623
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
1624
            @nesting.push(resource)
1625 1626 1627

            with_scope_level(kind) do
              scope(parent_resource.resource_scope) { yield }
1628
            end
1629
          ensure
1630
            @nesting.pop
1631
            @scope[:scope_level_resource] = old_resource
1632 1633
          end

J
José Valim 已提交
1634
          def nested_options #:nodoc:
1635 1636
            options = { :as => parent_resource.member_name }
            options[:constraints] = {
1637 1638
              parent_resource.nested_param => param_constraint
            } if param_constraint?
1639 1640

            options
1641 1642
          end

1643 1644 1645 1646
          def nesting_depth #:nodoc:
            @nesting.size
          end

1647 1648 1649 1650
          def shallow_nesting_depth #:nodoc:
            @nesting.select(&:shallow?).size
          end

1651 1652
          def param_constraint? #:nodoc:
            @scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp)
1653 1654
          end

1655 1656
          def param_constraint #:nodoc:
            @scope[:constraints][parent_resource.param]
1657 1658
          end

J
José Valim 已提交
1659
          def canonical_action?(action, flag) #:nodoc:
1660
            flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
1661 1662
          end

1663 1664 1665 1666 1667 1668 1669
          def shallow_scope(path, options = {}) #:nodoc:
            old_name_prefix, old_path = @scope[:as], @scope[:path]
            @scope[:as], @scope[:path] = @scope[:shallow_prefix], @scope[:shallow_path]

            scope(path, options) { yield }
          ensure
            @scope[:as], @scope[:path] = old_name_prefix, old_path
1670 1671
          end

J
José Valim 已提交
1672
          def path_for_action(action, path) #:nodoc:
1673
            if canonical_action?(action, path.blank?)
1674
              @scope[:path].to_s
1675
            else
1676
              "#{@scope[:path]}/#{action_path(action, path)}"
1677 1678 1679
            end
          end

J
José Valim 已提交
1680
          def action_path(name, path = nil) #:nodoc:
1681
            name = name.to_sym if name.is_a?(String)
1682
            path || @scope[:path_names][name] || name.to_s
1683 1684
          end

J
José Valim 已提交
1685
          def prefix_name_for_action(as, action) #:nodoc:
1686
            if as
1687
              prefix = as
1688
            elsif !canonical_action?(action, @scope[:scope_level])
1689
              prefix = action
1690
            end
1691
            prefix.to_s.tr('-', '_') if prefix
1692 1693
          end

J
José Valim 已提交
1694
          def name_for_action(as, action) #:nodoc:
1695
            prefix = prefix_name_for_action(as, action)
1696
            prefix = Mapper.normalize_name(prefix) if prefix
1697 1698 1699
            name_prefix = @scope[:as]

            if parent_resource
1700
              return nil unless as || action
1701

1702 1703
              collection_name = parent_resource.collection_name
              member_name = parent_resource.member_name
1704
            end
1705

1706
            name = case @scope[:scope_level]
1707
            when :nested
1708
              [name_prefix, prefix]
1709
            when :collection
1710
              [prefix, name_prefix, collection_name]
1711
            when :new
1712 1713
              [prefix, :new, name_prefix, member_name]
            when :member
1714
              [prefix, name_prefix, member_name]
1715 1716
            when :root
              [name_prefix, collection_name, prefix]
1717
            else
1718
              [name_prefix, member_name, prefix]
1719
            end
1720

1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
            if candidate = name.select(&:present?).join("_").presence
              # If a name was not explicitly given, we check if it is valid
              # and return nil in case it isn't. Otherwise, we pass the invalid name
              # forward so the underlying router engine treats it and raises an exception.
              if as.nil?
                candidate unless @set.routes.find { |r| r.name == candidate } || candidate !~ /\A[_a-z]/i
              else
                candidate
              end
            end
1731
          end
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743

          def set_member_mappings_for_resource
            member do
              get :edit if parent_resource.actions.include?(:edit)
              get :show if parent_resource.actions.include?(:show)
              if parent_resource.actions.include?(:update)
                patch :update
                put   :update
              end
              delete :destroy if parent_resource.actions.include?(:destroy)
            end
          end
J
Joshua Peek 已提交
1744
      end
J
Joshua Peek 已提交
1745

1746
      # Routing Concerns allow you to declare common routes that can be reused
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
      # inside others resources and routes.
      #
      #   concern :commentable do
      #     resources :comments
      #   end
      #
      #   concern :image_attachable do
      #     resources :images, only: :index
      #   end
      #
      # These concerns are used in Resources routing:
      #
      #   resources :messages, concerns: [:commentable, :image_attachable]
      #
      # or in a scope or namespace:
      #
      #   namespace :posts do
      #     concerns :commentable
      #   end
1766
      module Concerns
1767
        # Define a routing concern using a name.
1768
        #
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
        # Concerns may be defined inline, using a block, or handled by
        # another object, by passing that object as the second parameter.
        #
        # The concern object, if supplied, should respond to <tt>call</tt>,
        # which will receive two parameters:
        #
        #   * The current mapper
        #   * A hash of options which the concern object may use
        #
        # Options may also be used by concerns defined in a block by accepting
        # a block parameter. So, using a block, you might do something as
        # simple as limit the actions available on certain resources, passing
        # standard resource options through the concern:
        #
        #   concern :commentable do |options|
        #     resources :comments, options
        #   end
        #
        #   resources :posts, concerns: :commentable
        #   resources :archived_posts do
        #     # Don't allow comments on archived posts
        #     concerns :commentable, only: [:index, :show]
1791 1792
        #   end
        #
1793 1794 1795
        # Or, using a callable object, you might implement something more
        # specific to your application, which would be out of place in your
        # routes file.
1796
        #
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
        #   # purchasable.rb
        #   class Purchasable
        #     def initialize(defaults = {})
        #       @defaults = defaults
        #     end
        #
        #     def call(mapper, options = {})
        #       options = @defaults.merge(options)
        #       mapper.resources :purchases
        #       mapper.resources :receipts
        #       mapper.resources :returns if options[:returnable]
1808 1809 1810
        #     end
        #   end
        #
1811 1812 1813 1814 1815 1816 1817 1818
        #   # routes.rb
        #   concern :purchasable, Purchasable.new(returnable: true)
        #
        #   resources :toys, concerns: :purchasable
        #   resources :electronics, concerns: :purchasable
        #   resources :pets do
        #     concerns :purchasable, returnable: false
        #   end
1819
        #
1820 1821 1822
        # Any routing helpers can be used inside a concern. If using a
        # callable, they're accessible from the Mapper that's passed to
        # <tt>call</tt>.
1823
        def concern(name, callable = nil, &block)
1824 1825
          callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) }
          @concerns[name] = callable
1826 1827
        end

1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
        # Use the named concerns
        #
        #   resources :posts do
        #     concerns :commentable
        #   end
        #
        # concerns also work in any routes helper that you want to use:
        #
        #   namespace :posts do
        #     concerns :commentable
        #   end
1839 1840 1841
        def concerns(*args)
          options = args.extract_options!
          args.flatten.each do |name|
1842
            if concern = @concerns[name]
1843
              concern.call(self, options)
1844 1845 1846 1847 1848 1849 1850
            else
              raise ArgumentError, "No concern named #{name} was found!"
            end
          end
        end
      end

1851 1852 1853
      def initialize(set) #:nodoc:
        @set = set
        @scope = { :path_names => @set.resources_path_names }
1854
        @concerns = {}
1855
        @nesting = []
1856 1857
      end

1858 1859
      include Base
      include HttpHelpers
1860
      include Redirection
1861
      include Scoping
1862
      include Concerns
1863
      include Resources
J
Joshua Peek 已提交
1864 1865
    end
  end
J
Joshua Peek 已提交
1866
end