mapper.rb 63.9 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
        IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix, :format]
64
        ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
65

66
        attr_reader :scope, :options, :requirements, :conditions, :defaults
67
        attr_reader :to, :default_controller, :default_action
68

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

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

78 79
          path = normalize_path! path, options[:format]
          ast  = path_ast path
A
Aaron Patterson 已提交
80 81
          path_params = path_params ast
          @options = normalize_options!(options, path_params, ast)
82
          normalize_requirements!(path_params)
83
          normalize_conditions!(path_params, path, ast)
84
          normalize_defaults!
85
        end
J
Joshua Peek 已提交
86

87
        def to_route
88
          [ app, conditions, requirements, defaults, options[:as], options[:anchor] ]
89
        end
J
Joshua Peek 已提交
90

91
        private
92

93 94
          def normalize_path!(path, format)
            path = Mapper.normalize_path(path)
95

96 97 98 99 100 101
            if format == true
              "#{path}.:format"
            elsif optional_format?(path, format)
              "#{path}(.:format)"
            else
              path
102 103 104
            end
          end

105 106
          def optional_format?(path, format)
            format != false && !path.include?(':format') && !path.end_with?('/')
107 108
          end

A
Aaron Patterson 已提交
109
          def normalize_options!(options, path_params, path_ast)
110 111
            # Add a constraint for wildcard route to make it non-greedy and match the
            # optional format part of the route by default
A
Aaron Patterson 已提交
112 113 114 115
            if options[:format] != false
              path_ast.grep(Journey::Nodes::Star) do |node|
                options[node.name.to_sym] ||= /.+?/
              end
116 117
            end

118
            if path_params.include?(:controller)
119 120 121 122 123 124
              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' }
125
              options[:controller] ||= /.+?/
126
            end
127

A
Aaron Patterson 已提交
128 129 130
            if to.respond_to? :call
              options
            else
131
              options.merge!(default_controller_and_action(path_params))
A
Aaron Patterson 已提交
132
            end
133 134
          end

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

142
            if options[:format] == true
143
              @requirements[:format] ||= /.+/
144 145 146 147 148
            elsif Regexp === options[:format]
              @requirements[:format] = options[:format]
            elsif String === options[:format]
              @requirements[:format] = Regexp.compile(options[:format])
            end
149
          end
150

Y
Yves Senn 已提交
151 152 153 154 155 156 157 158 159 160
          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

161 162 163
          def normalize_defaults!
            @defaults.merge!(scope[:defaults]) if scope[:defaults]
            @defaults.merge!(options[:defaults]) if options[:defaults]
164

165
            options.each do |key, default|
A
Akshay Vishnoi 已提交
166 167 168
              unless Regexp === default || IGNORE_OPTIONS.include?(key)
                @defaults[key] = default
              end
169 170
            end

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

181 182 183 184
            if Regexp === options[:format]
              @defaults[:format] = nil
            elsif String === options[:format]
              @defaults[:format] = options[:format]
185
            end
186
          end
187

188
          def verify_callable_constraint(callable_constraint)
189 190 191
            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
192 193
          end

194
          def normalize_conditions!(path_params, path, ast)
195
            @conditions[:path_info] = path
196
            @conditions[:parsed_path_info] = ast
197

198
            constraints.each do |key, condition|
199
              unless path_params.include?(key) || key == :controller
A
Akshay Vishnoi 已提交
200 201
                @conditions[key] = condition
              end
202
            end
J
Joshua Peek 已提交
203

204
            required_defaults = []
205
            options.each do |key, required_default|
206
              unless path_params.include?(key) || IGNORE_OPTIONS.include?(key) || Regexp === required_default
207
                required_defaults << key
A
Akshay Vishnoi 已提交
208
              end
209
            end
210
            @conditions[:required_defaults] = required_defaults
211

212 213 214 215
            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" \
216 217
                    "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" \
218 219 220
                    "  Instead of: match \"controller#action\"\n" \
                    "  Do: get \"controller#action\""
              raise msg
221
            end
222

223
            if via = options[:via]
224
              @conditions[:request_method] = Array(via).map { |m| m.to_s.dasherize.upcase }
225 226 227
            end
          end

228
          def app
229 230
            return to if Redirect === to

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

242
          def default_controller_and_action(path_params)
A
Aaron Patterson 已提交
243
            controller, action = get_controller_and_action(default_controller,
244 245 246 247
              default_action,
              to,
              @scope[:module]
            )
A
Aaron Patterson 已提交
248

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

A
Aaron Patterson 已提交
254 255
                raise ArgumentError, message
              }
256
            end
257

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

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

275 276
          def get_controller_and_action(controller, action, to, modyoule)
            case to
A
Aaron Patterson 已提交
277 278 279
            when Symbol then action = to.to_s
            when /#/    then controller, action = to.split('#')
            when String then controller = to
280 281 282 283 284 285 286 287 288 289 290 291
            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 已提交
292
          def translate_controller(controller)
293 294
            return controller if Regexp === controller
            return controller.to_s if controller =~ /\A[a-z_0-9][a-z_0-9\/]*\z/
295

296
            yield
297 298
          end

299
          def blocks
300 301
            if options[:constraints].present? && !options[:constraints].is_a?(Hash)
              [options[:constraints]]
302
            else
303
              scope[:blocks] || []
304 305
            end
          end
J
Joshua Peek 已提交
306

307
          def constraints
308 309
            @constraints ||= {}.tap do |constraints|
              constraints.merge!(scope[:constraints]) if scope[:constraints]
310

311 312 313 314 315
              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)
316
            end
317
          end
J
Joshua Peek 已提交
318

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

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

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

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

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

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

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

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

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

          raise "A rack application must be specified" unless path

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1069
          alias :member_name :singular
1070

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

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

1081
          alias :collection_scope :path
1082 1083

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

1087 1088
          alias :shallow_scope :member_scope

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

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

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

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

          def shallow?
            @shallow
          end
1108 1109 1110
        end

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

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

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

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

          alias :member_name :singular
          alias :collection_name :singular

          alias :member_scope :path
          alias :nested_scope :path
1135 1136
        end

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

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

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

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

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

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

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

1182
            set_member_mappings_for_resource
1183 1184
          end

J
Joshua Peek 已提交
1185
          self
1186 1187
        end

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

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

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

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

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

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

1341
            set_member_mappings_for_resource
1342 1343
          end

J
Joshua Peek 已提交
1344
          self
1345 1346
        end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1504
          action = action.to_s.dup
1505

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

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

1518
          mapping = Mapping.new(@scope, URI.parser.escape(path), options)
1519 1520
          app, conditions, requirements, defaults, as, anchor = mapping.to_route
          @set.add_route(app, conditions, requirements, defaults, as, anchor)
J
Joshua Peek 已提交
1521 1522
        end

1523 1524 1525 1526 1527 1528 1529 1530 1531
        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

1532
          if @scope[:scope_level] == :resources
1533 1534
            with_scope_level(:root) do
              scope(parent_resource.path) do
1535 1536 1537 1538 1539 1540
                super(options)
              end
            end
          else
            super(options)
          end
1541 1542
        end

1543
        protected
1544

1545
          def parent_resource #:nodoc:
1546 1547 1548
            @scope[:scope_level_resource]
          end

J
José Valim 已提交
1549
          def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
1550 1551 1552 1553 1554
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

1555 1556 1557 1558 1559 1560 1561
            if options.delete(:shallow)
              shallow do
                send(method, resources.pop, options, &block)
              end
              return true
            end

1562 1563 1564 1565 1566
            if resource_scope?
              nested { send(method, resources.pop, options, &block) }
              return true
            end

1567
            options.keys.each do |k|
1568 1569 1570
              (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
            end

1571 1572 1573
            scope_options = options.slice!(*RESOURCE_OPTIONS)
            unless scope_options.empty?
              scope(scope_options) do
1574 1575 1576 1577 1578
                send(method, resources.pop, options, &block)
              end
              return true
            end

1579 1580 1581 1582
            unless action_options?(options)
              options.merge!(scope_action_options) if scope_action_options?
            end

1583 1584 1585
            false
          end

J
José Valim 已提交
1586
          def action_options?(options) #:nodoc:
1587 1588 1589
            options[:only] || options[:except]
          end

J
José Valim 已提交
1590
          def scope_action_options? #:nodoc:
A
Aaron Patterson 已提交
1591
            @scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
1592 1593
          end

J
José Valim 已提交
1594
          def scope_action_options #:nodoc:
1595 1596 1597
            @scope[:options].slice(:only, :except)
          end

J
José Valim 已提交
1598
          def resource_scope? #:nodoc:
1599
            RESOURCE_SCOPES.include? @scope[:scope_level]
1600 1601
          end

J
José Valim 已提交
1602
          def resource_method_scope? #:nodoc:
1603
            RESOURCE_METHOD_SCOPES.include? @scope[:scope_level]
1604 1605
          end

1606 1607 1608 1609
          def nested_scope? #:nodoc:
            @scope[:scope_level] == :nested
          end

1610
          def with_exclusive_scope
1611
            begin
1612 1613
              old_name_prefix, old_path = @scope[:as], @scope[:path]
              @scope[:as], @scope[:path] = nil, nil
1614

1615 1616 1617
              with_scope_level(:exclusive) do
                yield
              end
1618
            ensure
1619
              @scope[:as], @scope[:path] = old_name_prefix, old_path
1620 1621 1622
            end
          end

1623
          def with_scope_level(kind)
J
Joshua Peek 已提交
1624 1625 1626 1627 1628
            old, @scope[:scope_level] = @scope[:scope_level], kind
            yield
          ensure
            @scope[:scope_level] = old
          end
1629

1630
          def resource_scope(kind, resource) #:nodoc:
1631
            resource.shallow = @scope[:shallow]
1632
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
1633
            @nesting.push(resource)
1634 1635 1636

            with_scope_level(kind) do
              scope(parent_resource.resource_scope) { yield }
1637
            end
1638
          ensure
1639
            @nesting.pop
1640
            @scope[:scope_level_resource] = old_resource
1641 1642
          end

J
José Valim 已提交
1643
          def nested_options #:nodoc:
1644 1645
            options = { :as => parent_resource.member_name }
            options[:constraints] = {
1646 1647
              parent_resource.nested_param => param_constraint
            } if param_constraint?
1648 1649

            options
1650 1651
          end

1652 1653 1654 1655
          def nesting_depth #:nodoc:
            @nesting.size
          end

1656 1657 1658 1659
          def shallow_nesting_depth #:nodoc:
            @nesting.select(&:shallow?).size
          end

1660 1661
          def param_constraint? #:nodoc:
            @scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp)
1662 1663
          end

1664 1665
          def param_constraint #:nodoc:
            @scope[:constraints][parent_resource.param]
1666 1667
          end

J
José Valim 已提交
1668
          def canonical_action?(action, flag) #:nodoc:
1669
            flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
1670 1671
          end

1672 1673 1674 1675 1676 1677 1678
          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
1679 1680
          end

J
José Valim 已提交
1681
          def path_for_action(action, path) #:nodoc:
1682
            if canonical_action?(action, path.blank?)
1683
              @scope[:path].to_s
1684
            else
1685
              "#{@scope[:path]}/#{action_path(action, path)}"
1686 1687 1688
            end
          end

J
José Valim 已提交
1689
          def action_path(name, path = nil) #:nodoc:
1690
            name = name.to_sym if name.is_a?(String)
1691
            path || @scope[:path_names][name] || name.to_s
1692 1693
          end

J
José Valim 已提交
1694
          def prefix_name_for_action(as, action) #:nodoc:
1695
            if as
1696
              prefix = as
1697
            elsif !canonical_action?(action, @scope[:scope_level])
1698
              prefix = action
1699
            end
1700
            prefix.to_s.tr('-', '_') if prefix
1701 1702
          end

J
José Valim 已提交
1703
          def name_for_action(as, action) #:nodoc:
1704
            prefix = prefix_name_for_action(as, action)
1705
            prefix = Mapper.normalize_name(prefix) if prefix
1706 1707 1708
            name_prefix = @scope[:as]

            if parent_resource
1709
              return nil unless as || action
1710

1711 1712
              collection_name = parent_resource.collection_name
              member_name = parent_resource.member_name
1713
            end
1714

1715
            name = case @scope[:scope_level]
1716
            when :nested
1717
              [name_prefix, prefix]
1718
            when :collection
1719
              [prefix, name_prefix, collection_name]
1720
            when :new
1721 1722
              [prefix, :new, name_prefix, member_name]
            when :member
1723
              [prefix, name_prefix, member_name]
1724 1725
            when :root
              [name_prefix, collection_name, prefix]
1726
            else
1727
              [name_prefix, member_name, prefix]
1728
            end
1729

1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
            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
1740
          end
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752

          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 已提交
1753
      end
J
Joshua Peek 已提交
1754

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

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

1860 1861 1862
      def initialize(set) #:nodoc:
        @set = set
        @scope = { :path_names => @set.resources_path_names }
1863
        @concerns = {}
1864
        @nesting = []
1865 1866
      end

1867 1868
      include Base
      include HttpHelpers
1869
      include Redirection
1870
      include Scoping
1871
      include Concerns
1872
      include Resources
J
Joshua Peek 已提交
1873 1874
    end
  end
J
Joshua Peek 已提交
1875
end