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
require 'action_dispatch/routing/endpoint'
10

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

19
      class Constraints < Endpoint #:nodoc:
20
        attr_reader :app, :constraints
21

22
        def initialize(app, constraints, dispatcher_p)
23 24 25 26
          # 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.
27
          if app.is_a?(self.class)
28 29 30 31
            constraints += app.constraints
            app = app.app
          end

32
          @dispatcher = dispatcher_p
33

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

37 38
        def dispatcher?; @dispatcher; end

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

46
        def serve(req)
47 48 49 50 51 52 53
          return [ 404, {'X-Cascade' => 'pass'}, [] ] unless matches?(req)

          if dispatcher?
            @app.serve req
          else
            @app.call req.env
          end
54
        end
55 56 57

        private
          def constraint_args(constraint, request)
58
            constraint.arity == 1 ? [request] : [request.path_parameters, request]
59
          end
60 61
      end

62
      class Mapping #:nodoc:
63
        ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
64

A
Aaron Patterson 已提交
65
        attr_reader :options, :requirements, :conditions, :defaults
66
        attr_reader :to, :default_controller, :default_action, :as, :anchor
67

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

71
          @defaults = (scope[:defaults] || {}).merge options.delete(:defaults) || {}
72

73
          options = scope[:options].merge(options) if scope[:options]
74
          @to                 = options.delete :to
75 76
          @default_controller = options[:controller] || scope[:controller]
          @default_action     = options[:action] || scope[:action]
77 78
          @as                 = options.delete :as
          @anchor             = options.delete :anchor
79

A
Aaron Patterson 已提交
80
          formatted = options.delete :format
81
          via = Array(options.delete(:via) { [] })
82 83
          options_constraints = options.delete :constraints
          @blocks = blocks(options_constraints, scope[:blocks])
84 85

          path = normalize_path! path, formatted
86
          ast  = path_ast path
A
Aaron Patterson 已提交
87
          path_params = path_params ast
88
          @options = normalize_options!(options, formatted, path_params, ast, scope[:module])
89

90

91
          constraints = constraints(options_constraints,
92 93
                                    (scope[:constraints] || {}),
                                    path_params)
94

95
          normalize_requirements!(path_params, formatted, constraints)
96 97 98 99

          @conditions[:path_info] = path
          @conditions[:parsed_path_info] = ast

100
          add_request_method(via, @conditions)
101
          normalize_defaults!(formatted, options_constraints)
102
        end
J
Joshua Peek 已提交
103

104
        def to_route
105
          [ app(@blocks), conditions, requirements, defaults, as, anchor ]
106
        end
J
Joshua Peek 已提交
107

108
        private
109

110 111
          def normalize_path!(path, format)
            path = Mapper.normalize_path(path)
112

113 114 115 116 117 118
            if format == true
              "#{path}.:format"
            elsif optional_format?(path, format)
              "#{path}(.:format)"
            else
              path
119 120 121
            end
          end

122 123
          def optional_format?(path, format)
            format != false && !path.include?(':format') && !path.end_with?('/')
124 125
          end

126
          def normalize_options!(options, formatted, path_params, path_ast, modyoule)
127 128
            # Add a constraint for wildcard route to make it non-greedy and match the
            # optional format part of the route by default
129
            if formatted != false
A
Aaron Patterson 已提交
130 131 132
              path_ast.grep(Journey::Nodes::Star) do |node|
                options[node.name.to_sym] ||= /.+?/
              end
133 134
            end

135
            if path_params.include?(:controller)
136
              raise ArgumentError, ":controller segment is not allowed within a namespace block" if modyoule
137 138 139 140 141

              # 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' }
142
              options[:controller] ||= /.+?/
143
            end
144

A
Aaron Patterson 已提交
145 146 147
            if to.respond_to? :call
              options
            else
148
              options.merge!(default_controller_and_action(path_params, modyoule))
A
Aaron Patterson 已提交
149
            end
150 151
          end

152
          def normalize_requirements!(path_params, formatted, constraints)
153 154 155 156 157 158 159
            constraints.each_pair do |key, requirement|
              if path_params.include?(key) || key == :controller
                verify_regexp_requirement(requirement) if requirement.is_a?(Regexp)
                @requirements[key] = requirement
              else
                @conditions[key] = requirement
              end
160
            end
161

162
            if formatted == true
163
              @requirements[:format] ||= /.+/
164 165 166 167
            elsif Regexp === formatted
              @requirements[:format] = formatted
            elsif String === formatted
              @requirements[:format] = Regexp.compile(formatted)
168
            end
169
          end
170

Y
Yves Senn 已提交
171 172 173 174 175 176 177 178 179 180
          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

181
          def normalize_defaults!(formatted, options_constraints)
182
            options.each do |key, default|
A
Aaron Patterson 已提交
183
              unless Regexp === default
A
Akshay Vishnoi 已提交
184 185
                @defaults[key] = default
              end
186 187
            end

188 189
            if options_constraints.is_a?(Hash)
              options_constraints.each do |key, default|
A
Akshay Vishnoi 已提交
190 191 192
                if URL_OPTIONS.include?(key) && (String === default || Fixnum === default)
                  @defaults[key] ||= default
                end
193
              end
194 195
            elsif options_constraints
              verify_callable_constraint(options_constraints)
196 197
            end

198
            if Regexp === formatted
199
              @defaults[:format] = nil
200 201
            elsif String === formatted
              @defaults[:format] = formatted
202
            end
203
          end
204

205
          def verify_callable_constraint(callable_constraint)
206 207 208
            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
209 210
          end

211
          def add_request_method(via, conditions)
212 213 214 215 216 217 218 219 220
            return if via == [:all]

            if via.empty?
              msg = "You should not use the `match` method in your router without specifying an HTTP method.\n" \
                    "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" \
                    "  Instead of: match \"controller#action\"\n" \
                    "  Do: get \"controller#action\""
              raise ArgumentError, msg
221
            end
222 223

            conditions[:request_method] = via.map { |m| m.to_s.dasherize.upcase }
224 225
          end

226
          def app(blocks)
227 228
            return to if Redirect === to

229
            if to.respond_to?(:call)
230
              Constraints.new(to, blocks, false)
231
            else
232
              if blocks.any?
233
                Constraints.new(dispatcher, blocks, true)
234 235 236
              else
                dispatcher
              end
237
            end
238 239
          end

240
          def default_controller_and_action(path_params, modyoule)
A
Aaron Patterson 已提交
241
            controller, action = get_controller_and_action(default_controller,
242 243
              default_action,
              to,
244
              modyoule
245
            )
A
Aaron Patterson 已提交
246

247
            hash = check_part(:controller, controller, path_params, {}) do |part|
A
Aaron Patterson 已提交
248
              translate_controller(part) {
249 250
                message = "'#{part}' 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"
251

A
Aaron Patterson 已提交
252 253
                raise ArgumentError, message
              }
254
            end
255

256
            check_part(:action, action, path_params, hash) { |part|
A
Aaron Patterson 已提交
257
              part.is_a?(Regexp) ? part : part.to_s
258
            }
259
          end
260

261
          def check_part(name, part, path_params, hash)
262
            if part
A
Aaron Patterson 已提交
263
              hash[name] = yield(part)
264
            else
265
              unless path_params.include?(name)
266
                message = "Missing :#{name} key on routes definition, please check your routes."
267 268
                raise ArgumentError, message
              end
269
            end
270
            hash
271
          end
272

273 274
          def get_controller_and_action(controller, action, to, modyoule)
            case to
A
Aaron Patterson 已提交
275 276 277
            when Symbol then action = to.to_s
            when /#/    then controller, action = to.split('#')
            when String then controller = to
278 279 280 281 282 283 284 285 286 287 288 289
            end

            if modyoule && !controller.is_a?(Regexp)
              if controller =~ %r{\A/}
                controller = controller[1..-1]
              else
                controller = [modyoule, controller].compact.join("/")
              end
            end
            [controller, action]
          end

A
Aaron Patterson 已提交
290
          def translate_controller(controller)
291 292
            return controller if Regexp === controller
            return controller.to_s if controller =~ /\A[a-z_0-9][a-z_0-9\/]*\z/
293

294
            yield
295 296
          end

297 298 299
          def blocks(options_constraints, scope_blocks)
            if options_constraints.present? && !options_constraints.is_a?(Hash)
              [options_constraints]
300
            else
301
              scope_blocks || []
302 303
            end
          end
J
Joshua Peek 已提交
304

305 306
          def constraints(option_constraints, constraints, path_params)
            required_defaults = []
307
            options.each_pair do |key, option|
A
Aaron Patterson 已提交
308 309 310 311
              if Regexp === option
                constraints[key] = option
              else
                required_defaults << key unless path_params.include?(key)
312
              end
313
            end
314
            @conditions[:required_defaults] = required_defaults
315 316 317

            constraints.merge!(option_constraints) if option_constraints.is_a?(Hash)
            constraints
318
          end
J
Joshua Peek 已提交
319

A
Aaron Patterson 已提交
320 321
          def path_params(ast)
            ast.grep(Journey::Nodes::Symbol).map { |n| n.name.to_sym }
322
          end
323

324 325 326
          def path_ast(path)
            parser = Journey::Parser.new
            parser.parse path
327 328 329
          end

          def dispatcher
330
            Routing::RouteSet::Dispatcher.new(defaults)
331 332
          end
      end
333

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

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

347
      module Base
348 349
        # You can specify what Rails should route "/" to with the root method:
        #
A
AvnerCohen 已提交
350
        #   root to: 'pages#main'
351
        #
352
        # For options, see +match+, as +root+ uses it internally.
353
        #
354 355 356 357
        # You can also pass a string which will expand
        #
        #   root 'pages#main'
        #
358 359 360
        # 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.
361
        def root(options = {})
362
          match '/', { :as => :root, :via => :get }.merge!(options)
363
        end
364

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

523 524
        # Mount a Rack-based application to be used within the application.
        #
A
AvnerCohen 已提交
525
        #   mount SomeRackApp, at: "some_route"
526 527 528
        #
        # Alternatively:
        #
R
Ryan Bigg 已提交
529
        #   mount(SomeRackApp => "some_route")
530
        #
531 532
        # For options, see +match+, as +mount+ uses it internally.
        #
533 534 535 536 537
        # 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 已提交
538
        #   mount(SomeRackApp => "some_route", as: "exciting")
539 540 541
        #
        # This will generate the +exciting_path+ and +exciting_url+ helpers
        # which can be used to navigate to this mounted app.
542 543 544 545
        def mount(app, options = nil)
          if options
            path = options.delete(:at)
          else
546 547 548 549
            unless Hash === app
              raise ArgumentError, "must be called with mount point"
            end

550
            options = app
551
            app, path = options.find { |k, _| k.respond_to?(:call) }
552 553 554 555 556
            options.delete(app) if app
          end

          raise "A rack application must be specified" unless path

P
Pratik Naik 已提交
557
          options[:as]  ||= app_name(app)
558
          target_as       = name_for_action(options[:as], path)
P
Pratik Naik 已提交
559
          options[:via] ||= :all
560

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

563
          define_generate_prefix(app, target_as)
564 565 566
          self
        end

567 568 569 570
        def default_url_options=(options)
          @set.default_url_options = options
        end
        alias_method :default_url_options, :default_url_options=
571

572 573 574 575 576 577
        def with_default_scope(scope, &block)
          scope(scope) do
            instance_exec(&block)
          end
        end

578 579 580 581 582
        # Query if the following named route was already defined.
        def has_named_route?(name)
          @set.named_routes.routes[name.to_sym]
        end

583 584 585
        private
          def app_name(app)
            return unless app.respond_to?(:routes)
586 587 588 589 590

            if app.respond_to?(:railtie_name)
              app.railtie_name
            else
              class_name = app.class.is_a?(Class) ? app.name : app.class.name
591
              ActiveSupport::Inflector.underscore(class_name).tr("/", "_")
592
            end
593 594 595
          end

          def define_generate_prefix(app, name)
596
            return unless app.respond_to?(:routes) && app.routes.respond_to?(:define_mounted_helper)
597 598

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

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

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

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

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

648
        # Define a route that only recognizes HTTP DELETE.
C
Cesar Carruitero 已提交
649
        # For supported arguments, see match[rdoc-ref:Base#match]
650
        #
A
AvnerCohen 已提交
651
        #   delete 'broccoli', to: 'food#broccoli'
652
        def delete(*args, &block)
653
          map_method(:delete, args, &block)
654 655 656
        end

        private
657
          def map_method(method, args, &block)
658
            options = args.extract_options!
659
            options[:via] = method
660
            match(*args, options, &block)
661 662 663 664
            self
          end
      end

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

754
          options[:path] = args.flatten.join('/') if args.any?
755
          options[:constraints] ||= {}
756

757
          unless nested_scope?
758 759
            options[:shallow_path] ||= options[:path] if options.key?(:path)
            options[:shallow_prefix] ||= options[:as] if options.key?(:as)
760 761
          end

762
          if options[:constraints].is_a?(Hash)
763 764 765 766 767
            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)
768 769
          else
            block, options[:constraints] = options[:constraints], {}
770 771
          end

772 773 774 775 776 777 778 779 780 781
          SCOPE_OPTIONS.each do |option|
            if option == :blocks
              value = block
            elsif option == :options
              value = options
            else
              value = options.delete(option)
            end

            if value
782 783 784
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
785 786 787 788 789
          end

          yield
          self
        ensure
790
          @scope.merge!(recover)
791 792
        end

793 794 795
        # Scopes routes to a specific controller
        #
        #   controller "food" do
A
AvnerCohen 已提交
796
        #     match "bacon", action: "bacon"
797
        #   end
798 799 800
        def controller(controller, options={})
          options[:controller] = controller
          scope(options) { yield }
801 802
        end

803 804 805 806 807 808 809 810
        # Scopes routes to a specific namespace. For example:
        #
        #   namespace :admin do
        #     resources :posts
        #   end
        #
        # This generates the following routes:
        #
811 812 813 814 815
        #       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
816
        #        admin_post PATCH/PUT /admin/posts/:id(.:format)      admin/posts#update
817
        #        admin_post DELETE    /admin/posts/:id(.:format)      admin/posts#destroy
818
        #
819
        # === Options
820
        #
821 822
        # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
        # options all default to the name of the namespace.
823
        #
824 825
        # For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
        # <tt>Resources#resources</tt>.
826
        #
827
        #   # accessible through /sekret/posts rather than /admin/posts
A
AvnerCohen 已提交
828
        #   namespace :admin, path: "sekret" do
829 830
        #     resources :posts
        #   end
831
        #
S
Sebastian Martinez 已提交
832
        #   # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
A
AvnerCohen 已提交
833
        #   namespace :admin, module: "sekret" do
834 835
        #     resources :posts
        #   end
836
        #
S
Sebastian Martinez 已提交
837
        #   # generates +sekret_posts_path+ rather than +admin_posts_path+
A
AvnerCohen 已提交
838
        #   namespace :admin, as: "sekret" do
839 840
        #     resources :posts
        #   end
841
        def namespace(path, options = {})
842
          path = path.to_s
843 844 845 846 847 848 849 850 851 852

          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 }
853
        end
854

R
Ryan Bigg 已提交
855 856 857 858
        # === 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 已提交
859
        #   constraints(id: /\d+\.\d+/) do
R
Ryan Bigg 已提交
860 861 862 863 864
        #     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.
865
        #
R
R.T. Lechow 已提交
866
        # You may use this to also restrict other parameters:
R
Ryan Bigg 已提交
867 868
        #
        #   resources :posts do
A
AvnerCohen 已提交
869
        #     constraints(post_id: /\d+\.\d+/) do
R
Ryan Bigg 已提交
870 871
        #       resources :comments
        #     end
J
James Miller 已提交
872
        #   end
R
Ryan Bigg 已提交
873 874 875 876 877
        #
        # === Restricting based on IP
        #
        # Routes can also be constrained to an IP or a certain range of IP addresses:
        #
A
AvnerCohen 已提交
878
        #   constraints(ip: /192\.168\.\d+\.\d+/) do
R
Ryan Bigg 已提交
879 880 881 882 883 884 885 886
        #     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 已提交
887
        # Requests to routes can be constrained based on specific criteria:
R
Ryan Bigg 已提交
888 889 890 891 892 893 894 895 896 897
        #
        #    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
898
        #      def self.matches?(request)
R
Ryan Bigg 已提交
899 900 901 902 903 904 905 906 907 908 909
        #        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
910 911 912 913
        def constraints(constraints = {})
          scope(:constraints => constraints) { yield }
        end

R
Ryan Bigg 已提交
914
        # Allows you to set default parameters for a route, such as this:
A
AvnerCohen 已提交
915 916
        #   defaults id: 'home' do
        #     match 'scoped_pages/(:id)', to: 'pages#show'
917
        #   end
R
Ryan Bigg 已提交
918
        # Using this, the +:id+ parameter here will default to 'home'.
919 920 921 922
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

923
        private
J
José Valim 已提交
924
          def merge_path_scope(parent, child) #:nodoc:
925
            Mapper.normalize_path("#{parent}/#{child}")
926 927
          end

J
José Valim 已提交
928
          def merge_shallow_path_scope(parent, child) #:nodoc:
929 930 931
            Mapper.normalize_path("#{parent}/#{child}")
          end

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

J
José Valim 已提交
936
          def merge_shallow_prefix_scope(parent, child) #:nodoc:
937 938 939
            parent ? "#{parent}_#{child}" : child
          end

J
José Valim 已提交
940
          def merge_module_scope(parent, child) #:nodoc:
941 942 943
            parent ? "#{parent}/#{child}" : child
          end

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

948 949 950 951
          def merge_action_scope(parent, child) #:nodoc:
            child
          end

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

J
José Valim 已提交
956
          def merge_constraints_scope(parent, child) #:nodoc:
957 958 959
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
960
          def merge_defaults_scope(parent, child) #:nodoc:
961 962 963
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
964
          def merge_blocks_scope(parent, child) #:nodoc:
965 966 967
            merged = parent ? parent.dup : []
            merged << child if child
            merged
968 969
          end

J
José Valim 已提交
970
          def merge_options_scope(parent, child) #:nodoc:
971
            (parent || {}).except(*override_keys(child)).merge!(child)
972
          end
973

J
José Valim 已提交
974
          def merge_shallow_scope(parent, child) #:nodoc:
975 976
            child ? true : false
          end
977

J
José Valim 已提交
978
          def override_keys(child) #:nodoc:
979 980
            child.key?(:only) || child.key?(:except) ? [:only, :except] : []
          end
981 982
      end

983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
      # 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 已提交
1007 1008
      # <tt>app/controllers/admin</tt> directory, and you can group them together
      # in your router:
1009 1010 1011 1012 1013
      #
      #   namespace "admin" do
      #     resources :posts, :comments
      #   end
      #
S
Sebastian Martinez 已提交
1014 1015
      # 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
1016 1017
      # overrides this restriction, e.g:
      #
A
AvnerCohen 已提交
1018
      #   resources :articles, id: /[^\/]+/
1019
      #
S
Sebastian Martinez 已提交
1020
      # This allows any character other than a slash as part of your +:id+.
1021
      #
J
Joshua Peek 已提交
1022
      module Resources
1023 1024
        # CANONICAL_ACTIONS holds all actions that does not need a prefix or
        # a path appended since they fit properly in their scope level.
1025
        VALID_ON_OPTIONS  = [:new, :collection, :member]
1026
        RESOURCE_OPTIONS  = [:as, :controller, :path, :only, :except, :param, :concerns]
1027
        CANONICAL_ACTIONS = %w(index create new show update destroy)
1028 1029
        RESOURCE_METHOD_SCOPES = [:collection, :member, :new]
        RESOURCE_SCOPES = [:resource, :resources]
1030

1031
        class Resource #:nodoc:
1032
          attr_reader :controller, :path, :options, :param
1033 1034

          def initialize(entities, options = {})
1035
            @name       = entities.to_s
1036 1037 1038
            @path       = (options[:path] || @name).to_s
            @controller = (options[:controller] || @name).to_s
            @as         = options[:as]
1039
            @param      = (options[:param] || :id).to_sym
1040
            @options    = options
1041
            @shallow    = false
1042 1043
          end

1044
          def default_actions
1045
            [:index, :create, :new, :show, :update, :destroy, :edit]
1046 1047
          end

1048
          def actions
1049
            if only = @options[:only]
1050
              Array(only).map(&:to_sym)
1051
            elsif except = @options[:except]
1052 1053 1054 1055 1056 1057
              default_actions - Array(except).map(&:to_sym)
            else
              default_actions
            end
          end

1058
          def name
1059
            @as || @name
1060 1061
          end

1062
          def plural
1063
            @plural ||= name.to_s
1064 1065 1066
          end

          def singular
1067
            @singular ||= name.to_s.singularize
1068 1069
          end

1070
          alias :member_name :singular
1071

1072
          # Checks for uncountable plurals, and appends "_index" if the plural
1073
          # and singular form are the same.
1074
          def collection_name
1075
            singular == plural ? "#{plural}_index" : plural
1076 1077
          end

1078
          def resource_scope
1079
            { :controller => controller }
1080 1081
          end

1082
          alias :collection_scope :path
1083 1084

          def member_scope
1085
            "#{path}/:#{param}"
1086 1087
          end

1088 1089
          alias :shallow_scope :member_scope

1090
          def new_scope(new_path)
1091
            "#{path}/#{new_path}"
1092 1093
          end

1094 1095 1096 1097
          def nested_param
            :"#{singular}_#{param}"
          end

1098
          def nested_scope
1099
            "#{path}/:#{nested_param}"
1100
          end
1101

1102 1103 1104 1105 1106 1107 1108
          def shallow=(value)
            @shallow = value
          end

          def shallow?
            @shallow
          end
1109 1110 1111
        end

        class SingletonResource < Resource #:nodoc:
1112
          def initialize(entities, options)
1113
            super
1114
            @as         = nil
1115 1116
            @controller = (options[:controller] || plural).to_s
            @as         = options[:as]
1117 1118
          end

1119 1120 1121 1122
          def default_actions
            [:show, :create, :update, :destroy, :new, :edit]
          end

1123 1124
          def plural
            @plural ||= name.to_s.pluralize
1125 1126
          end

1127 1128
          def singular
            @singular ||= name.to_s
1129
          end
1130 1131 1132 1133 1134 1135

          alias :member_name :singular
          alias :collection_name :singular

          alias :member_scope :path
          alias :nested_scope :path
1136 1137
        end

1138 1139 1140 1141
        def resources_path_names(options)
          @scope[:path_names].merge!(options)
        end

1142 1143 1144 1145 1146 1147
        # 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:
        #
1148
        #   resource :profile
1149 1150
        #
        # creates six different routes in your application, all mapping to
1151
        # the +Profiles+ controller (note that the controller is named after
1152 1153
        # the plural):
        #
1154 1155 1156 1157 1158 1159
        #   GET       /profile/new
        #   POST      /profile
        #   GET       /profile
        #   GET       /profile/edit
        #   PATCH/PUT /profile
        #   DELETE    /profile
1160
        #
1161
        # === Options
1162
        # Takes same options as +resources+.
J
Joshua Peek 已提交
1163
        def resource(*resources, &block)
1164
          options = resources.extract_options!.dup
J
Joshua Peek 已提交
1165

1166
          if apply_common_behavior_for(:resource, resources, options, &block)
1167 1168 1169
            return self
          end

1170
          resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
1171
            yield if block_given?
1172

1173 1174
            concerns(options[:concerns]) if options[:concerns]

1175
            collection do
1176
              post :create
1177
            end if parent_resource.actions.include?(:create)
1178

1179
            new do
1180
              get :new
1181
            end if parent_resource.actions.include?(:new)
1182

1183
            set_member_mappings_for_resource
1184 1185
          end

J
Joshua Peek 已提交
1186
          self
1187 1188
        end

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

1324
          if apply_common_behavior_for(:resources, resources, options, &block)
1325 1326 1327
            return self
          end

1328
          resource_scope(:resources, Resource.new(resources.pop, options)) do
1329
            yield if block_given?
J
Joshua Peek 已提交
1330

1331 1332
            concerns(options[:concerns]) if options[:concerns]

1333
            collection do
1334 1335
              get  :index if parent_resource.actions.include?(:index)
              post :create if parent_resource.actions.include?(:create)
1336
            end
1337

1338
            new do
1339
              get :new
1340
            end if parent_resource.actions.include?(:new)
1341

1342
            set_member_mappings_for_resource
1343 1344
          end

J
Joshua Peek 已提交
1345
          self
1346 1347
        end

1348 1349 1350 1351 1352 1353 1354 1355 1356
        # 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 已提交
1357
        # with GET, and route to the search action of +PhotosController+. It will also
1358 1359
        # create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
        # route helpers.
J
Joshua Peek 已提交
1360
        def collection
1361 1362
          unless resource_scope?
            raise ArgumentError, "can't use collection outside resource(s) scope"
1363 1364
          end

1365 1366 1367 1368
          with_scope_level(:collection) do
            scope(parent_resource.collection_scope) do
              yield
            end
J
Joshua Peek 已提交
1369
          end
1370
        end
J
Joshua Peek 已提交
1371

1372 1373 1374 1375 1376 1377 1378 1379 1380
        # 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 已提交
1381
        # preview action of +PhotosController+. It will also create the
1382
        # <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
J
Joshua Peek 已提交
1383
        def member
1384 1385
          unless resource_scope?
            raise ArgumentError, "can't use member outside resource(s) scope"
J
Joshua Peek 已提交
1386
          end
J
Joshua Peek 已提交
1387

1388
          with_scope_level(:member) do
1389 1390 1391 1392
            if shallow?
              shallow_scope(parent_resource.member_scope) { yield }
            else
              scope(parent_resource.member_scope) { yield }
1393
            end
1394 1395 1396 1397 1398 1399 1400
          end
        end

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

1402 1403 1404 1405
          with_scope_level(:new) do
            scope(parent_resource.new_scope(action_path(:new))) do
              yield
            end
J
Joshua Peek 已提交
1406
          end
J
Joshua Peek 已提交
1407 1408
        end

1409
        def nested
1410 1411
          unless resource_scope?
            raise ArgumentError, "can't use nested outside resource(s) scope"
1412 1413 1414
          end

          with_scope_level(:nested) do
1415
            if shallow? && shallow_nesting_depth > 1
1416
              shallow_scope(parent_resource.nested_scope, nested_options) { yield }
1417
            else
1418
              scope(parent_resource.nested_scope, nested_options) { yield }
1419 1420 1421 1422
            end
          end
        end

1423
        # See ActionDispatch::Routing::Mapper::Scoping#namespace
1424
        def namespace(path, options = {})
1425
          if resource_scope?
1426 1427 1428 1429 1430 1431
            nested { super }
          else
            super
          end
        end

1432
        def shallow
1433
          scope(:shallow => true) do
1434 1435 1436 1437
            yield
          end
        end

1438 1439 1440 1441
        def shallow?
          parent_resource.instance_of?(Resource) && @scope[:shallow]
        end

1442
        # match 'path' => 'controller#action'
R
Rafael Mendonça França 已提交
1443
        # match 'path', to: 'controller#action'
1444
        # match 'path', 'otherpath', on: :member, via: :get
1445 1446 1447
        def match(path, *rest)
          if rest.empty? && Hash === path
            options  = path
1448
            path, to = options.find { |name, _value| name.is_a?(String) }
1449 1450
            options[:to] = to
            options.delete(path)
1451 1452 1453 1454 1455 1456
            paths = [path]
          else
            options = rest.pop || {}
            paths = [path] + rest
          end

1457 1458
          options[:anchor] = true unless options.key?(:anchor)

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

1463 1464 1465 1466
          if @scope[:controller] && @scope[:action]
            options[:to] ||= "#{@scope[:controller]}##{@scope[:action]}"
          end

1467 1468 1469
          paths.each do |_path|
            route_options = options.dup
            route_options[:path] ||= _path if _path.is_a?(String)
1470 1471 1472 1473

            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')
1474
              route_options[:to].tr!("-", "_")
1475 1476
            end

1477 1478
            decomposed_match(_path, route_options)
          end
1479 1480
          self
        end
1481

1482 1483 1484 1485
        def using_match_shorthand?(path, options)
          path && (options[:to] || options[:action]).nil? && path =~ %r{/[\w/]+$}
        end

1486
        def decomposed_match(path, options) # :nodoc:
A
Aaron Patterson 已提交
1487 1488
          if on = options.delete(:on)
            send(on) { decomposed_match(path, options) }
1489
          else
A
Aaron Patterson 已提交
1490 1491 1492 1493 1494 1495 1496 1497
            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 已提交
1498
          end
1499
        end
J
Joshua Peek 已提交
1500

1501
        def add_route(action, options) # :nodoc:
1502
          path = path_for_action(action, options.delete(:path))
1503 1504
          raise ArgumentError, "path is required" if path.blank?

1505
          action = action.to_s.dup
1506

1507
          if action =~ /^[\w\-\/]+$/
1508
            options[:action] ||= action.tr('-', '_') unless action.include?("/")
1509
          else
1510 1511 1512
            action = nil
          end

1513
          if !options.fetch(:as, true)
1514 1515 1516
            options.delete(:as)
          else
            options[:as] = name_for_action(options[:as], action)
J
Joshua Peek 已提交
1517
          end
J
Joshua Peek 已提交
1518

1519
          options.delete :only
A
Aaron Patterson 已提交
1520 1521 1522 1523 1524
          options.delete :except
          options.delete :shallow_path
          options.delete :shallow_prefix
          options.delete :shallow

1525
          mapping = Mapping.new(@scope, URI.parser.escape(path), options)
1526 1527
          app, conditions, requirements, defaults, as, anchor = mapping.to_route
          @set.add_route(app, conditions, requirements, defaults, as, anchor)
J
Joshua Peek 已提交
1528 1529
        end

1530 1531 1532 1533 1534 1535 1536 1537 1538
        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

1539
          if @scope[:scope_level] == :resources
1540 1541
            with_scope_level(:root) do
              scope(parent_resource.path) do
1542 1543 1544 1545 1546 1547
                super(options)
              end
            end
          else
            super(options)
          end
1548 1549
        end

1550
        protected
1551

1552
          def parent_resource #:nodoc:
1553 1554 1555
            @scope[:scope_level_resource]
          end

J
José Valim 已提交
1556
          def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
1557 1558 1559 1560 1561
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

1562 1563 1564 1565 1566 1567 1568
            if options.delete(:shallow)
              shallow do
                send(method, resources.pop, options, &block)
              end
              return true
            end

1569 1570 1571 1572 1573
            if resource_scope?
              nested { send(method, resources.pop, options, &block) }
              return true
            end

1574
            options.keys.each do |k|
1575 1576 1577
              (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
            end

1578 1579 1580
            scope_options = options.slice!(*RESOURCE_OPTIONS)
            unless scope_options.empty?
              scope(scope_options) do
1581 1582 1583 1584 1585
                send(method, resources.pop, options, &block)
              end
              return true
            end

1586 1587 1588 1589
            unless action_options?(options)
              options.merge!(scope_action_options) if scope_action_options?
            end

1590 1591 1592
            false
          end

J
José Valim 已提交
1593
          def action_options?(options) #:nodoc:
1594 1595 1596
            options[:only] || options[:except]
          end

J
José Valim 已提交
1597
          def scope_action_options? #:nodoc:
A
Aaron Patterson 已提交
1598
            @scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
1599 1600
          end

J
José Valim 已提交
1601
          def scope_action_options #:nodoc:
1602 1603 1604
            @scope[:options].slice(:only, :except)
          end

J
José Valim 已提交
1605
          def resource_scope? #:nodoc:
1606
            RESOURCE_SCOPES.include? @scope[:scope_level]
1607 1608
          end

J
José Valim 已提交
1609
          def resource_method_scope? #:nodoc:
1610
            RESOURCE_METHOD_SCOPES.include? @scope[:scope_level]
1611 1612
          end

1613 1614 1615 1616
          def nested_scope? #:nodoc:
            @scope[:scope_level] == :nested
          end

1617
          def with_exclusive_scope
1618
            begin
1619 1620
              old_name_prefix, old_path = @scope[:as], @scope[:path]
              @scope[:as], @scope[:path] = nil, nil
1621

1622 1623 1624
              with_scope_level(:exclusive) do
                yield
              end
1625
            ensure
1626
              @scope[:as], @scope[:path] = old_name_prefix, old_path
1627 1628 1629
            end
          end

1630
          def with_scope_level(kind)
J
Joshua Peek 已提交
1631 1632 1633 1634 1635
            old, @scope[:scope_level] = @scope[:scope_level], kind
            yield
          ensure
            @scope[:scope_level] = old
          end
1636

1637
          def resource_scope(kind, resource) #:nodoc:
1638
            resource.shallow = @scope[:shallow]
1639
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
1640
            @nesting.push(resource)
1641 1642 1643

            with_scope_level(kind) do
              scope(parent_resource.resource_scope) { yield }
1644
            end
1645
          ensure
1646
            @nesting.pop
1647
            @scope[:scope_level_resource] = old_resource
1648 1649
          end

J
José Valim 已提交
1650
          def nested_options #:nodoc:
1651 1652
            options = { :as => parent_resource.member_name }
            options[:constraints] = {
1653 1654
              parent_resource.nested_param => param_constraint
            } if param_constraint?
1655 1656

            options
1657 1658
          end

1659 1660 1661 1662
          def nesting_depth #:nodoc:
            @nesting.size
          end

1663 1664 1665 1666
          def shallow_nesting_depth #:nodoc:
            @nesting.select(&:shallow?).size
          end

1667 1668
          def param_constraint? #:nodoc:
            @scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp)
1669 1670
          end

1671 1672
          def param_constraint #:nodoc:
            @scope[:constraints][parent_resource.param]
1673 1674
          end

J
José Valim 已提交
1675
          def canonical_action?(action, flag) #:nodoc:
1676
            flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
1677 1678
          end

1679 1680 1681 1682 1683 1684 1685
          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
1686 1687
          end

J
José Valim 已提交
1688
          def path_for_action(action, path) #:nodoc:
1689
            if canonical_action?(action, path.blank?)
1690
              @scope[:path].to_s
1691
            else
1692
              "#{@scope[:path]}/#{action_path(action, path)}"
1693 1694 1695
            end
          end

J
José Valim 已提交
1696
          def action_path(name, path = nil) #:nodoc:
1697
            name = name.to_sym if name.is_a?(String)
1698
            path || @scope[:path_names][name] || name.to_s
1699 1700
          end

J
José Valim 已提交
1701
          def prefix_name_for_action(as, action) #:nodoc:
1702
            if as
1703
              prefix = as
1704
            elsif !canonical_action?(action, @scope[:scope_level])
1705
              prefix = action
1706
            end
1707
            prefix.to_s.tr('-', '_') if prefix
1708 1709
          end

J
José Valim 已提交
1710
          def name_for_action(as, action) #:nodoc:
1711
            prefix = prefix_name_for_action(as, action)
1712
            prefix = Mapper.normalize_name(prefix) if prefix
1713 1714 1715
            name_prefix = @scope[:as]

            if parent_resource
1716
              return nil unless as || action
1717

1718 1719
              collection_name = parent_resource.collection_name
              member_name = parent_resource.member_name
1720
            end
1721

1722
            name = case @scope[:scope_level]
1723
            when :nested
1724
              [name_prefix, prefix]
1725
            when :collection
1726
              [prefix, name_prefix, collection_name]
1727
            when :new
1728 1729
              [prefix, :new, name_prefix, member_name]
            when :member
1730
              [prefix, name_prefix, member_name]
1731 1732
            when :root
              [name_prefix, collection_name, prefix]
1733
            else
1734
              [name_prefix, member_name, prefix]
1735
            end
1736

1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
            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
1747
          end
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759

          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 已提交
1760
      end
J
Joshua Peek 已提交
1761

1762
      # Routing Concerns allow you to declare common routes that can be reused
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
      # 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
1782
      module Concerns
1783
        # Define a routing concern using a name.
1784
        #
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
        # 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]
1807 1808
        #   end
        #
1809 1810 1811
        # Or, using a callable object, you might implement something more
        # specific to your application, which would be out of place in your
        # routes file.
1812
        #
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
        #   # 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]
1824 1825 1826
        #     end
        #   end
        #
1827 1828 1829 1830 1831 1832 1833 1834
        #   # routes.rb
        #   concern :purchasable, Purchasable.new(returnable: true)
        #
        #   resources :toys, concerns: :purchasable
        #   resources :electronics, concerns: :purchasable
        #   resources :pets do
        #     concerns :purchasable, returnable: false
        #   end
1835
        #
1836 1837 1838
        # 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>.
1839
        def concern(name, callable = nil, &block)
1840 1841
          callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) }
          @concerns[name] = callable
1842 1843
        end

1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
        # 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
1855 1856 1857
        def concerns(*args)
          options = args.extract_options!
          args.flatten.each do |name|
1858
            if concern = @concerns[name]
1859
              concern.call(self, options)
1860 1861 1862 1863 1864 1865 1866
            else
              raise ArgumentError, "No concern named #{name} was found!"
            end
          end
        end
      end

1867 1868 1869
      def initialize(set) #:nodoc:
        @set = set
        @scope = { :path_names => @set.resources_path_names }
1870
        @concerns = {}
1871
        @nesting = []
1872 1873
      end

1874 1875
      include Base
      include HttpHelpers
1876
      include Redirection
1877
      include Scoping
1878
      include Concerns
1879
      include Resources
J
Joshua Peek 已提交
1880 1881
    end
  end
J
Joshua Peek 已提交
1882
end