mapper.rb 60.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

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

18
      class Constraints #:nodoc:
19
        def self.new(app, constraints, request = Rack::Request)
20
          if constraints.any?
21
            super(app, constraints, request)
22 23 24 25 26
          else
            app
          end
        end

27
        attr_reader :app, :constraints
28

29 30
        def initialize(app, constraints, request)
          @app, @constraints, @request = app, constraints, request
31 32
        end

33
        def matches?(env)
34
          req = @request.new(env)
35

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

        def call(env)
          matches?(env) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ]
46
        end
47 48 49 50 51

        private
          def constraint_args(constraint, request)
            constraint.arity == 1 ? [request] : [request.symbolized_path_parameters, request]
          end
52 53
      end

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

59
        attr_reader :scope, :path, :options, :requirements, :conditions, :defaults
60

61 62 63
        def initialize(set, scope, path, options)
          @set, @scope, @path, @options = set, scope, path, options
          @requirements, @conditions, @defaults = {}, {}, {}
64

65
          normalize_options!
66
          normalize_path!
67 68
          normalize_requirements!
          normalize_conditions!
69
          normalize_defaults!
70
        end
J
Joshua Peek 已提交
71

72
        def to_route
73
          [ app, conditions, requirements, defaults, options[:as], options[:anchor] ]
74
        end
J
Joshua Peek 已提交
75

76
        private
77

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
          def normalize_path!
            raise ArgumentError, "path is required" if @path.blank?
            @path = Mapper.normalize_path(@path)

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

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

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

97
          def normalize_options!
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
            @options.reverse_merge!(scope[:options]) if scope[:options]
            path_without_format = path.sub(/\(\.:format\)$/, '')

            # Add a constraint for wildcard route to make it non-greedy and match the
            # optional format part of the route by default
            if path_without_format.match(WILDCARD_PATH) && @options[:format] != false
              @options[$1.to_sym] ||= /.+?/
            end

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

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

117
            @options.merge!(default_controller_and_action)
118 119 120 121 122
          end

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

127
            if options[:format] == true
128
              @requirements[:format] ||= /.+/
129 130 131 132 133
            elsif Regexp === options[:format]
              @requirements[:format] = options[:format]
            elsif String === options[:format]
              @requirements[:format] = Regexp.compile(options[:format])
            end
134
          end
135

Y
Yves Senn 已提交
136 137 138 139 140 141 142 143 144 145
          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

146 147 148
          def normalize_defaults!
            @defaults.merge!(scope[:defaults]) if scope[:defaults]
            @defaults.merge!(options[:defaults]) if options[:defaults]
149

150
            options.each do |key, default|
A
Akshay Vishnoi 已提交
151 152 153
              unless Regexp === default || IGNORE_OPTIONS.include?(key)
                @defaults[key] = default
              end
154 155
            end

156 157
            if options[:constraints].is_a?(Hash)
              options[:constraints].each do |key, default|
A
Akshay Vishnoi 已提交
158 159 160
                if URL_OPTIONS.include?(key) && (String === default || Fixnum === default)
                  @defaults[key] ||= default
                end
161
              end
162 163
            end

164 165 166 167
            if Regexp === options[:format]
              @defaults[:format] = nil
            elsif String === options[:format]
              @defaults[:format] = options[:format]
168
            end
169
          end
170

171
          def normalize_conditions!
172
            @conditions[:path_info] = path
173

174
            constraints.each do |key, condition|
A
Akshay Vishnoi 已提交
175 176 177
              unless segment_keys.include?(key) || key == :controller
                @conditions[key] = condition
              end
178
            end
J
Joshua Peek 已提交
179

180
            required_defaults = []
181
            options.each do |key, required_default|
A
Akshay Vishnoi 已提交
182
              unless segment_keys.include?(key) || IGNORE_OPTIONS.include?(key) || Regexp === required_default
183
                required_defaults << key
A
Akshay Vishnoi 已提交
184
              end
185
            end
186
            @conditions[:required_defaults] = required_defaults
187

188 189 190 191
            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" \
192 193
                    "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" \
194 195 196
                    "  Instead of: match \"controller#action\"\n" \
                    "  Do: get \"controller#action\""
              raise msg
197
            end
198

199
            if via = options[:via]
200
              @conditions[:request_method] = Array(via).map { |m| m.to_s.dasherize.upcase }
201 202 203
            end
          end

204 205 206 207
          def app
            Constraints.new(endpoint, blocks, @set.request_class)
          end

208
          def default_controller_and_action
209
            if to.respond_to?(:call)
210 211
              { }
            else
212
              if to.is_a?(String)
213
                controller, action = to.split('#')
214 215
              elsif to.is_a?(Symbol)
                action = to.to_s
216
              end
J
Joshua Peek 已提交
217

218 219
              controller ||= default_controller
              action     ||= default_action
220

221 222 223 224 225 226
              if @scope[:module] && !controller.is_a?(Regexp)
                if controller =~ %r{\A/}
                  controller = controller[1..-1]
                else
                  controller = [@scope[:module], controller].compact.join("/").presence
                end
227
              end
228

229 230 231 232
              if controller.is_a?(String) && controller =~ %r{\A/}
                raise ArgumentError, "controller name should not start with a slash"
              end

233 234
              controller = controller.to_s unless controller.is_a?(Regexp)
              action     = action.to_s     unless action.is_a?(Regexp)
235

236
              if controller.blank? && segment_keys.exclude?(:controller)
237 238
                message = "Missing :controller key on routes definition, please check your routes."
                raise ArgumentError, message
239
              end
J
Joshua Peek 已提交
240

241
              if action.blank? && segment_keys.exclude?(:action)
242 243
                message = "Missing :action key on routes definition, please check your routes."
                raise ArgumentError, message
244
              end
J
Joshua Peek 已提交
245

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

A
Aaron Patterson 已提交
252
              hash = {}
A
Aaron Patterson 已提交
253 254
              hash[:controller] = controller unless controller.blank?
              hash[:action]     = action unless action.blank?
A
Aaron Patterson 已提交
255
              hash
256 257
            end
          end
258

259
          def blocks
260 261
            if options[:constraints].present? && !options[:constraints].is_a?(Hash)
              [options[:constraints]]
262
            else
263
              scope[:blocks] || []
264 265
            end
          end
J
Joshua Peek 已提交
266

267
          def constraints
268 269
            @constraints ||= {}.tap do |constraints|
              constraints.merge!(scope[:constraints]) if scope[:constraints]
270

271 272 273 274 275
              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)
276
            end
277
          end
J
Joshua Peek 已提交
278

279
          def segment_keys
280 281 282 283 284 285
            @segment_keys ||= path_pattern.names.map{ |s| s.to_sym }
          end

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

287 288 289 290 291 292 293 294 295 296
          def strexp
            Journey::Router::Strexp.compile(path, requirements, SEPARATORS)
          end

          def endpoint
            to.respond_to?(:call) ? to : dispatcher
          end

          def dispatcher
            Routing::RouteSet::Dispatcher.new(:defaults => defaults)
297
          end
298

299
          def to
300
            options[:to]
301
          end
J
Joshua Peek 已提交
302

303
          def default_controller
304
            options[:controller] || scope[:controller]
305
          end
306 307

          def default_action
308
            options[:action] || scope[:action]
309
          end
310
      end
311

312
      # Invokes Journey::Router::Utils.normalize_path and ensure that
313 314
      # (:locale) becomes (/:locale) instead of /(:locale). Except
      # for root cases, where the latter is the correct one.
315
      def self.normalize_path(path)
316
        path = Journey::Router::Utils.normalize_path(path)
317
        path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$}
318 319 320
        path
      end

321
      def self.normalize_name(name)
322
        normalize_path(name)[1..-1].tr("/", "_")
323 324
      end

325
      module Base
326 327
        # You can specify what Rails should route "/" to with the root method:
        #
A
AvnerCohen 已提交
328
        #   root to: 'pages#main'
329
        #
330
        # For options, see +match+, as +root+ uses it internally.
331
        #
332 333 334 335
        # You can also pass a string which will expand
        #
        #   root 'pages#main'
        #
336 337 338
        # 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.
339
        def root(options = {})
340
          match '/', { :as => :root, :via => :get }.merge!(options)
341
        end
342

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

475 476
        # Mount a Rack-based application to be used within the application.
        #
A
AvnerCohen 已提交
477
        #   mount SomeRackApp, at: "some_route"
478 479 480
        #
        # Alternatively:
        #
R
Ryan Bigg 已提交
481
        #   mount(SomeRackApp => "some_route")
482
        #
483 484
        # For options, see +match+, as +mount+ uses it internally.
        #
485 486 487 488 489
        # 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 已提交
490
        #   mount(SomeRackApp => "some_route", as: "exciting")
491 492 493
        #
        # This will generate the +exciting_path+ and +exciting_url+ helpers
        # which can be used to navigate to this mounted app.
494 495 496 497
        def mount(app, options = nil)
          if options
            path = options.delete(:at)
          else
498 499 500 501
            unless Hash === app
              raise ArgumentError, "must be called with mount point"
            end

502
            options = app
503
            app, path = options.find { |k, _| k.respond_to?(:call) }
504 505 506 507 508
            options.delete(app) if app
          end

          raise "A rack application must be specified" unless path

P
Pratik Naik 已提交
509
          options[:as]  ||= app_name(app)
510
          target_as       = name_for_action(options[:as], path)
P
Pratik Naik 已提交
511
          options[:via] ||= :all
512

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

515
          define_generate_prefix(app, target_as)
516 517 518
          self
        end

519 520 521 522
        def default_url_options=(options)
          @set.default_url_options = options
        end
        alias_method :default_url_options, :default_url_options=
523

524 525 526 527 528 529
        def with_default_scope(scope, &block)
          scope(scope) do
            instance_exec(&block)
          end
        end

530 531 532 533 534
        # Query if the following named route was already defined.
        def has_named_route?(name)
          @set.named_routes.routes[name.to_sym]
        end

535 536 537
        private
          def app_name(app)
            return unless app.respond_to?(:routes)
538 539 540 541 542

            if app.respond_to?(:railtie_name)
              app.railtie_name
            else
              class_name = app.class.is_a?(Class) ? app.name : app.class.name
543
              ActiveSupport::Inflector.underscore(class_name).tr("/", "_")
544
            end
545 546 547
          end

          def define_generate_prefix(app, name)
548
            return unless app.respond_to?(:routes) && app.routes.respond_to?(:define_mounted_helper)
549 550

            _route = @set.named_routes.routes[name.to_sym]
P
Piotr Sarnacki 已提交
551 552
            _routes = @set
            app.routes.define_mounted_helper(name)
J
José Valim 已提交
553
            app.routes.singleton_class.class_eval do
554
              redefine_method :mounted? do
J
José Valim 已提交
555 556 557
                true
              end

558
              redefine_method :_generate_prefix do |options|
P
Piotr Sarnacki 已提交
559
                prefix_options = options.slice(*_route.segment_keys)
560 561
                # we must actually delete prefix segment keys to avoid passing them to next url_for
                _route.segment_keys.each { |k| options.delete(k) }
562
                _routes.url_helpers.send("#{name}_path", prefix_options)
563 564 565
              end
            end
          end
566 567 568
      end

      module HttpHelpers
569
        # Define a route that only recognizes HTTP GET.
C
Cesar Carruitero 已提交
570
        # For supported arguments, see match[rdoc-ref:Base#match]
571
        #
A
AvnerCohen 已提交
572
        #   get 'bacon', to: 'food#bacon'
573
        def get(*args, &block)
574
          map_method(:get, args, &block)
575 576
        end

577
        # Define a route that only recognizes HTTP POST.
C
Cesar Carruitero 已提交
578
        # For supported arguments, see match[rdoc-ref:Base#match]
579
        #
A
AvnerCohen 已提交
580
        #   post 'bacon', to: 'food#bacon'
581
        def post(*args, &block)
582
          map_method(:post, args, &block)
583 584
        end

585
        # Define a route that only recognizes HTTP PATCH.
C
Cesar Carruitero 已提交
586
        # For supported arguments, see match[rdoc-ref:Base#match]
587
        #
A
AvnerCohen 已提交
588
        #   patch 'bacon', to: 'food#bacon'
589 590 591 592
        def patch(*args, &block)
          map_method(:patch, args, &block)
        end

593
        # Define a route that only recognizes HTTP PUT.
C
Cesar Carruitero 已提交
594
        # For supported arguments, see match[rdoc-ref:Base#match]
595
        #
A
AvnerCohen 已提交
596
        #   put 'bacon', to: 'food#bacon'
597
        def put(*args, &block)
598
          map_method(:put, args, &block)
599 600
        end

601
        # Define a route that only recognizes HTTP DELETE.
C
Cesar Carruitero 已提交
602
        # For supported arguments, see match[rdoc-ref:Base#match]
603
        #
A
AvnerCohen 已提交
604
        #   delete 'broccoli', to: 'food#broccoli'
605
        def delete(*args, &block)
606
          map_method(:delete, args, &block)
607 608 609
        end

        private
610
          def map_method(method, args, &block)
611
            options = args.extract_options!
612
            options[:via] = method
613
            match(*args, options, &block)
614 615 616 617
            self
          end
      end

618 619 620
      # 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 已提交
621 622
      # the <tt>app/controllers/admin</tt> directory, and you can group them
      # together in your router:
623 624 625 626
      #
      #   namespace "admin" do
      #     resources :posts, :comments
      #   end
627
      #
628
      # This will create a number of routes for each of the posts and comments
S
Sebastian Martinez 已提交
629
      # controller. For <tt>Admin::PostsController</tt>, Rails will create:
630
      #
631 632 633 634 635
      #   GET       /admin/posts
      #   GET       /admin/posts/new
      #   POST      /admin/posts
      #   GET       /admin/posts/1
      #   GET       /admin/posts/1/edit
636
      #   PATCH/PUT /admin/posts/1
637
      #   DELETE    /admin/posts/1
638
      #
639
      # If you want to route /posts (without the prefix /admin) to
S
Sebastian Martinez 已提交
640
      # <tt>Admin::PostsController</tt>, you could use
641
      #
A
AvnerCohen 已提交
642
      #   scope module: "admin" do
643
      #     resources :posts
644 645 646
      #   end
      #
      # or, for a single case
647
      #
A
AvnerCohen 已提交
648
      #   resources :posts, module: "admin"
649
      #
S
Sebastian Martinez 已提交
650
      # If you want to route /admin/posts to +PostsController+
651
      # (without the Admin:: module prefix), you could use
652
      #
653
      #   scope "/admin" do
654
      #     resources :posts
655 656 657
      #   end
      #
      # or, for a single case
658
      #
A
AvnerCohen 已提交
659
      #   resources :posts, path: "/admin/posts"
660 661 662
      #
      # 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 已提交
663
      # +PostsController+:
664
      #
665 666 667 668 669
      #   GET       /admin/posts
      #   GET       /admin/posts/new
      #   POST      /admin/posts
      #   GET       /admin/posts/1
      #   GET       /admin/posts/1/edit
670
      #   PATCH/PUT /admin/posts/1
671
      #   DELETE    /admin/posts/1
672
      module Scoping
673
        # Scopes a set of routes to the given default options.
674 675 676
        #
        # Take the following route definition as an example:
        #
A
AvnerCohen 已提交
677
        #   scope path: ":account_id", as: "account" do
678 679 680 681
        #     resources :projects
        #   end
        #
        # This generates helpers such as +account_projects_path+, just like +resources+ does.
682 683
        # The difference here being that the routes generated are like /:account_id/projects,
        # rather than /accounts/:account_id/projects.
684
        #
685
        # === Options
686
        #
687
        # Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>.
688
        #
S
Sebastian Martinez 已提交
689
        #   # route /posts (without the prefix /admin) to <tt>Admin::PostsController</tt>
A
AvnerCohen 已提交
690
        #   scope module: "admin" do
691 692
        #     resources :posts
        #   end
693
        #
694
        #   # prefix the posts resource's requests with '/admin'
A
AvnerCohen 已提交
695
        #   scope path: "/admin" do
696 697
        #     resources :posts
        #   end
698
        #
S
Sebastian Martinez 已提交
699
        #   # prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+
A
AvnerCohen 已提交
700
        #   scope as: "sekret" do
701 702
        #     resources :posts
        #   end
703
        def scope(*args)
704
          options = args.extract_options!.dup
705
          recover = {}
706

707
          options[:path] = args.flatten.join('/') if args.any?
708
          options[:constraints] ||= {}
709

710
          if options[:constraints].is_a?(Hash)
711 712 713 714 715
            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)
716 717
          else
            block, options[:constraints] = options[:constraints], {}
718 719
          end

720 721 722 723 724 725 726 727 728 729
          SCOPE_OPTIONS.each do |option|
            if option == :blocks
              value = block
            elsif option == :options
              value = options
            else
              value = options.delete(option)
            end

            if value
730 731 732
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
733 734 735 736 737
          end

          yield
          self
        ensure
738
          @scope.merge!(recover)
739 740
        end

741 742 743
        # Scopes routes to a specific controller
        #
        #   controller "food" do
A
AvnerCohen 已提交
744
        #     match "bacon", action: "bacon"
745
        #   end
746 747 748
        def controller(controller, options={})
          options[:controller] = controller
          scope(options) { yield }
749 750
        end

751 752 753 754 755 756 757 758
        # Scopes routes to a specific namespace. For example:
        #
        #   namespace :admin do
        #     resources :posts
        #   end
        #
        # This generates the following routes:
        #
759 760 761 762 763
        #       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
764
        #        admin_post PATCH/PUT /admin/posts/:id(.:format)      admin/posts#update
765
        #        admin_post DELETE    /admin/posts/:id(.:format)      admin/posts#destroy
766
        #
767
        # === Options
768
        #
769 770
        # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
        # options all default to the name of the namespace.
771
        #
772 773
        # For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
        # <tt>Resources#resources</tt>.
774
        #
775
        #   # accessible through /sekret/posts rather than /admin/posts
A
AvnerCohen 已提交
776
        #   namespace :admin, path: "sekret" do
777 778
        #     resources :posts
        #   end
779
        #
S
Sebastian Martinez 已提交
780
        #   # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
A
AvnerCohen 已提交
781
        #   namespace :admin, module: "sekret" do
782 783
        #     resources :posts
        #   end
784
        #
S
Sebastian Martinez 已提交
785
        #   # generates +sekret_posts_path+ rather than +admin_posts_path+
A
AvnerCohen 已提交
786
        #   namespace :admin, as: "sekret" do
787 788
        #     resources :posts
        #   end
789
        def namespace(path, options = {})
790
          path = path.to_s
791 792 793
          options = { :path => path, :as => path, :module => path,
                      :shallow_path => path, :shallow_prefix => path }.merge!(options)
          scope(options) { yield }
794
        end
795

R
Ryan Bigg 已提交
796 797 798 799
        # === 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 已提交
800
        #   constraints(id: /\d+\.\d+/) do
R
Ryan Bigg 已提交
801 802 803 804 805
        #     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.
806
        #
R
R.T. Lechow 已提交
807
        # You may use this to also restrict other parameters:
R
Ryan Bigg 已提交
808 809
        #
        #   resources :posts do
A
AvnerCohen 已提交
810
        #     constraints(post_id: /\d+\.\d+/) do
R
Ryan Bigg 已提交
811 812
        #       resources :comments
        #     end
J
James Miller 已提交
813
        #   end
R
Ryan Bigg 已提交
814 815 816 817 818
        #
        # === Restricting based on IP
        #
        # Routes can also be constrained to an IP or a certain range of IP addresses:
        #
A
AvnerCohen 已提交
819
        #   constraints(ip: /192\.168\.\d+\.\d+/) do
R
Ryan Bigg 已提交
820 821 822 823 824 825 826 827
        #     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 已提交
828
        # Requests to routes can be constrained based on specific criteria:
R
Ryan Bigg 已提交
829 830 831 832 833 834 835 836 837 838
        #
        #    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
839
        #      def self.matches?(request)
R
Ryan Bigg 已提交
840 841 842 843 844 845 846 847 848 849 850
        #        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
851 852 853 854
        def constraints(constraints = {})
          scope(:constraints => constraints) { yield }
        end

R
Ryan Bigg 已提交
855
        # Allows you to set default parameters for a route, such as this:
A
AvnerCohen 已提交
856 857
        #   defaults id: 'home' do
        #     match 'scoped_pages/(:id)', to: 'pages#show'
858
        #   end
R
Ryan Bigg 已提交
859
        # Using this, the +:id+ parameter here will default to 'home'.
860 861 862 863
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

864
        private
J
José Valim 已提交
865
          def merge_path_scope(parent, child) #:nodoc:
866
            Mapper.normalize_path("#{parent}/#{child}")
867 868
          end

J
José Valim 已提交
869
          def merge_shallow_path_scope(parent, child) #:nodoc:
870 871 872
            Mapper.normalize_path("#{parent}/#{child}")
          end

J
José Valim 已提交
873
          def merge_as_scope(parent, child) #:nodoc:
874
            parent ? "#{parent}_#{child}" : child
875 876
          end

J
José Valim 已提交
877
          def merge_shallow_prefix_scope(parent, child) #:nodoc:
878 879 880
            parent ? "#{parent}_#{child}" : child
          end

J
José Valim 已提交
881
          def merge_module_scope(parent, child) #:nodoc:
882 883 884
            parent ? "#{parent}/#{child}" : child
          end

J
José Valim 已提交
885
          def merge_controller_scope(parent, child) #:nodoc:
886
            child
887 888
          end

889 890 891 892
          def merge_action_scope(parent, child) #:nodoc:
            child
          end

J
José Valim 已提交
893
          def merge_path_names_scope(parent, child) #:nodoc:
894 895 896
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
897
          def merge_constraints_scope(parent, child) #:nodoc:
898 899 900
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
901
          def merge_defaults_scope(parent, child) #:nodoc:
902 903 904
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
905
          def merge_blocks_scope(parent, child) #:nodoc:
906 907 908
            merged = parent ? parent.dup : []
            merged << child if child
            merged
909 910
          end

J
José Valim 已提交
911
          def merge_options_scope(parent, child) #:nodoc:
912
            (parent || {}).except(*override_keys(child)).merge!(child)
913
          end
914

J
José Valim 已提交
915
          def merge_shallow_scope(parent, child) #:nodoc:
916 917
            child ? true : false
          end
918

J
José Valim 已提交
919
          def override_keys(child) #:nodoc:
920 921
            child.key?(:only) || child.key?(:except) ? [:only, :except] : []
          end
922 923
      end

924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
      # 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 已提交
948 949
      # <tt>app/controllers/admin</tt> directory, and you can group them together
      # in your router:
950 951 952 953 954
      #
      #   namespace "admin" do
      #     resources :posts, :comments
      #   end
      #
S
Sebastian Martinez 已提交
955 956
      # 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
957 958
      # overrides this restriction, e.g:
      #
A
AvnerCohen 已提交
959
      #   resources :articles, id: /[^\/]+/
960
      #
S
Sebastian Martinez 已提交
961
      # This allows any character other than a slash as part of your +:id+.
962
      #
J
Joshua Peek 已提交
963
      module Resources
964 965
        # CANONICAL_ACTIONS holds all actions that does not need a prefix or
        # a path appended since they fit properly in their scope level.
966
        VALID_ON_OPTIONS  = [:new, :collection, :member]
967
        RESOURCE_OPTIONS  = [:as, :controller, :path, :only, :except, :param, :concerns]
968
        CANONICAL_ACTIONS = %w(index create new show update destroy)
969 970
        RESOURCE_METHOD_SCOPES = [:collection, :member, :new]
        RESOURCE_SCOPES = [:resource, :resources]
971

972
        class Resource #:nodoc:
973
          attr_reader :controller, :path, :options, :param
974 975

          def initialize(entities, options = {})
976
            @name       = entities.to_s
977 978 979
            @path       = (options[:path] || @name).to_s
            @controller = (options[:controller] || @name).to_s
            @as         = options[:as]
980
            @param      = (options[:param] || :id).to_sym
981
            @options    = options
982 983
          end

984
          def default_actions
985
            [:index, :create, :new, :show, :update, :destroy, :edit]
986 987
          end

988
          def actions
989
            if only = @options[:only]
990
              Array(only).map(&:to_sym)
991
            elsif except = @options[:except]
992 993 994 995 996 997
              default_actions - Array(except).map(&:to_sym)
            else
              default_actions
            end
          end

998
          def name
999
            @as || @name
1000 1001
          end

1002
          def plural
1003
            @plural ||= name.to_s
1004 1005 1006
          end

          def singular
1007
            @singular ||= name.to_s.singularize
1008 1009
          end

1010
          alias :member_name :singular
1011

1012
          # Checks for uncountable plurals, and appends "_index" if the plural
1013
          # and singular form are the same.
1014
          def collection_name
1015
            singular == plural ? "#{plural}_index" : plural
1016 1017
          end

1018
          def resource_scope
1019
            { :controller => controller }
1020 1021
          end

1022
          alias :collection_scope :path
1023 1024

          def member_scope
1025
            "#{path}/:#{param}"
1026 1027
          end

1028 1029
          alias :shallow_scope :member_scope

1030
          def new_scope(new_path)
1031
            "#{path}/#{new_path}"
1032 1033
          end

1034 1035 1036 1037
          def nested_param
            :"#{singular}_#{param}"
          end

1038
          def nested_scope
1039
            "#{path}/:#{nested_param}"
1040
          end
1041

1042 1043 1044
        end

        class SingletonResource < Resource #:nodoc:
1045
          def initialize(entities, options)
1046
            super
1047
            @as         = nil
1048 1049
            @controller = (options[:controller] || plural).to_s
            @as         = options[:as]
1050 1051
          end

1052 1053 1054 1055
          def default_actions
            [:show, :create, :update, :destroy, :new, :edit]
          end

1056 1057
          def plural
            @plural ||= name.to_s.pluralize
1058 1059
          end

1060 1061
          def singular
            @singular ||= name.to_s
1062
          end
1063 1064 1065 1066 1067 1068

          alias :member_name :singular
          alias :collection_name :singular

          alias :member_scope :path
          alias :nested_scope :path
1069 1070
        end

1071 1072 1073 1074
        def resources_path_names(options)
          @scope[:path_names].merge!(options)
        end

1075 1076 1077 1078 1079 1080
        # 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:
        #
1081
        #   resource :profile
1082 1083
        #
        # creates six different routes in your application, all mapping to
1084
        # the +Profiles+ controller (note that the controller is named after
1085 1086
        # the plural):
        #
1087 1088 1089 1090 1091 1092
        #   GET       /profile/new
        #   POST      /profile
        #   GET       /profile
        #   GET       /profile/edit
        #   PATCH/PUT /profile
        #   DELETE    /profile
1093
        #
1094
        # === Options
1095
        # Takes same options as +resources+.
J
Joshua Peek 已提交
1096
        def resource(*resources, &block)
1097
          options = resources.extract_options!.dup
J
Joshua Peek 已提交
1098

1099
          if apply_common_behavior_for(:resource, resources, options, &block)
1100 1101 1102
            return self
          end

1103
          resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
1104
            yield if block_given?
1105

1106 1107
            concerns(options[:concerns]) if options[:concerns]

1108
            collection do
1109
              post :create
1110
            end if parent_resource.actions.include?(:create)
1111

1112
            new do
1113
              get :new
1114
            end if parent_resource.actions.include?(:new)
1115

1116
            set_member_mappings_for_resource
1117 1118
          end

J
Joshua Peek 已提交
1119
          self
1120 1121
        end

1122 1123 1124 1125 1126 1127 1128 1129
        # 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 已提交
1130
        # the +Photos+ controller:
1131
        #
1132 1133 1134 1135 1136
        #   GET       /photos
        #   GET       /photos/new
        #   POST      /photos
        #   GET       /photos/:id
        #   GET       /photos/:id/edit
1137
        #   PATCH/PUT /photos/:id
1138
        #   DELETE    /photos/:id
1139
        #
1140 1141 1142 1143 1144 1145 1146 1147
        # Resources can also be nested infinitely by using this block syntax:
        #
        #   resources :photos do
        #     resources :comments
        #   end
        #
        # This generates the following comments routes:
        #
1148 1149 1150 1151 1152
        #   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
1153
        #   PATCH/PUT /photos/:photo_id/comments/:id
1154
        #   DELETE    /photos/:photo_id/comments/:id
1155
        #
1156
        # === Options
1157 1158
        # Takes same options as <tt>Base#match</tt> as well as:
        #
1159
        # [:path_names]
A
Aviv Ben-Yosef 已提交
1160 1161
        #   Allows you to change the segment component of the +edit+ and +new+ actions.
        #   Actions not specified are not changed.
1162
        #
A
AvnerCohen 已提交
1163
        #     resources :posts, path_names: { new: "brand_new" }
1164 1165
        #
        #   The above example will now change /posts/new to /posts/brand_new
1166
        #
1167 1168 1169
        # [:path]
        #   Allows you to change the path prefix for the resource.
        #
A
AvnerCohen 已提交
1170
        #     resources :posts, path: 'postings'
1171 1172 1173
        #
        #   The resource and all segments will now route to /postings instead of /posts
        #
1174 1175
        # [:only]
        #   Only generate routes for the given actions.
1176
        #
A
AvnerCohen 已提交
1177 1178
        #     resources :cows, only: :show
        #     resources :cows, only: [:show, :index]
1179
        #
1180 1181
        # [:except]
        #   Generate all routes except for the given actions.
1182
        #
A
AvnerCohen 已提交
1183 1184
        #     resources :cows, except: :show
        #     resources :cows, except: [:show, :index]
1185 1186 1187 1188 1189
        #
        # [:shallow]
        #   Generates shallow routes for nested resource(s). When placed on a parent resource,
        #   generates shallow routes for all nested resources.
        #
A
AvnerCohen 已提交
1190
        #     resources :posts, shallow: true do
1191 1192 1193 1194 1195 1196
        #       resources :comments
        #     end
        #
        #   Is the same as:
        #
        #     resources :posts do
A
AvnerCohen 已提交
1197
        #       resources :comments, except: [:show, :edit, :update, :destroy]
1198
        #     end
A
AvnerCohen 已提交
1199
        #     resources :comments, only: [:show, :edit, :update, :destroy]
1200 1201 1202 1203
        #
        #   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>.
1204 1205 1206 1207
        #
        # [:shallow_path]
        #   Prefixes nested shallow routes with the specified path.
        #
A
AvnerCohen 已提交
1208
        #     scope shallow_path: "sekret" do
1209
        #       resources :posts do
A
AvnerCohen 已提交
1210
        #         resources :comments, shallow: true
1211
        #       end
1212 1213 1214 1215
        #     end
        #
        #   The +comments+ resource here will have the following routes generated for it:
        #
1216 1217 1218 1219 1220
        #     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)
1221
        #     comment          PATCH/PUT /sekret/comments/:id(.:format)
1222
        #     comment          DELETE    /sekret/comments/:id(.:format)
1223
        #
1224 1225 1226
        # [:shallow_prefix]
        #   Prefixes nested shallow route names with specified prefix.
        #
A
AvnerCohen 已提交
1227
        #     scope shallow_prefix: "sekret" do
1228
        #       resources :posts do
A
AvnerCohen 已提交
1229
        #         resources :comments, shallow: true
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        #       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)
        #
1243
        # [:format]
1244
        #   Allows you to specify the default value for optional +format+
V
Vijay Dev 已提交
1245
        #   segment or disable it by supplying +false+.
1246
        #
1247
        # === Examples
1248
        #
S
Sebastian Martinez 已提交
1249
        #   # routes call <tt>Admin::PostsController</tt>
A
AvnerCohen 已提交
1250
        #   resources :posts, module: "admin"
1251
        #
1252
        #   # resource actions are at /admin/posts.
A
AvnerCohen 已提交
1253
        #   resources :posts, path: "admin/posts"
J
Joshua Peek 已提交
1254
        def resources(*resources, &block)
1255
          options = resources.extract_options!.dup
1256

1257
          if apply_common_behavior_for(:resources, resources, options, &block)
1258 1259 1260
            return self
          end

1261
          resource_scope(:resources, Resource.new(resources.pop, options)) do
1262
            yield if block_given?
J
Joshua Peek 已提交
1263

1264 1265
            concerns(options[:concerns]) if options[:concerns]

1266
            collection do
1267 1268
              get  :index if parent_resource.actions.include?(:index)
              post :create if parent_resource.actions.include?(:create)
1269
            end
1270

1271
            new do
1272
              get :new
1273
            end if parent_resource.actions.include?(:new)
1274

1275
            set_member_mappings_for_resource
1276 1277
          end

J
Joshua Peek 已提交
1278
          self
1279 1280
        end

1281 1282 1283 1284 1285 1286 1287 1288 1289
        # 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 已提交
1290
        # with GET, and route to the search action of +PhotosController+. It will also
1291 1292
        # create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
        # route helpers.
J
Joshua Peek 已提交
1293
        def collection
1294 1295
          unless resource_scope?
            raise ArgumentError, "can't use collection outside resource(s) scope"
1296 1297
          end

1298 1299 1300 1301
          with_scope_level(:collection) do
            scope(parent_resource.collection_scope) do
              yield
            end
J
Joshua Peek 已提交
1302
          end
1303
        end
J
Joshua Peek 已提交
1304

1305 1306 1307 1308 1309 1310 1311 1312 1313
        # 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 已提交
1314
        # preview action of +PhotosController+. It will also create the
1315
        # <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
J
Joshua Peek 已提交
1316
        def member
1317 1318
          unless resource_scope?
            raise ArgumentError, "can't use member outside resource(s) scope"
J
Joshua Peek 已提交
1319
          end
J
Joshua Peek 已提交
1320

1321 1322 1323 1324
          with_scope_level(:member) do
            scope(parent_resource.member_scope) do
              yield
            end
1325 1326 1327 1328 1329 1330 1331
          end
        end

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

1333 1334 1335 1336
          with_scope_level(:new) do
            scope(parent_resource.new_scope(action_path(:new))) do
              yield
            end
J
Joshua Peek 已提交
1337
          end
J
Joshua Peek 已提交
1338 1339
        end

1340
        def nested
1341 1342
          unless resource_scope?
            raise ArgumentError, "can't use nested outside resource(s) scope"
1343 1344 1345
          end

          with_scope_level(:nested) do
1346
            if shallow?
1347
              with_exclusive_scope do
1348
                if @scope[:shallow_path].blank?
1349
                  scope(parent_resource.nested_scope, nested_options) { yield }
1350
                else
1351
                  scope(@scope[:shallow_path], :as => @scope[:shallow_prefix]) do
1352
                    scope(parent_resource.nested_scope, nested_options) { yield }
1353 1354 1355 1356
                  end
                end
              end
            else
1357
              scope(parent_resource.nested_scope, nested_options) { yield }
1358 1359 1360 1361
            end
          end
        end

1362
        # See ActionDispatch::Routing::Mapper::Scoping#namespace
1363
        def namespace(path, options = {})
1364
          if resource_scope?
1365 1366 1367 1368 1369 1370
            nested { super }
          else
            super
          end
        end

1371
        def shallow
1372
          scope(:shallow => true, :shallow_path => @scope[:path]) do
1373 1374 1375 1376
            yield
          end
        end

1377 1378 1379 1380
        def shallow?
          parent_resource.instance_of?(Resource) && @scope[:shallow]
        end

1381
        # match 'path' => 'controller#action'
R
Rafael Mendonça França 已提交
1382
        # match 'path', to: 'controller#action'
1383
        # match 'path', 'otherpath', on: :member, via: :get
1384 1385 1386
        def match(path, *rest)
          if rest.empty? && Hash === path
            options  = path
1387
            path, to = options.find { |name, _value| name.is_a?(String) }
1388 1389
            options[:to] = to
            options.delete(path)
1390 1391 1392 1393 1394 1395
            paths = [path]
          else
            options = rest.pop || {}
            paths = [path] + rest
          end

1396 1397
          options[:anchor] = true unless options.key?(:anchor)

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

1402 1403 1404 1405
          if @scope[:controller] && @scope[:action]
            options[:to] ||= "#{@scope[:controller]}##{@scope[:action]}"
          end

1406 1407 1408
          paths.each do |_path|
            route_options = options.dup
            route_options[:path] ||= _path if _path.is_a?(String)
1409 1410 1411 1412 1413 1414

            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')
            end

1415 1416
            decomposed_match(_path, route_options)
          end
1417 1418
          self
        end
1419

1420 1421 1422 1423
        def using_match_shorthand?(path, options)
          path && (options[:to] || options[:action]).nil? && path =~ %r{/[\w/]+$}
        end

1424
        def decomposed_match(path, options) # :nodoc:
A
Aaron Patterson 已提交
1425 1426
          if on = options.delete(:on)
            send(on) { decomposed_match(path, options) }
1427
          else
A
Aaron Patterson 已提交
1428 1429 1430 1431 1432 1433 1434 1435
            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 已提交
1436
          end
1437
        end
J
Joshua Peek 已提交
1438

1439
        def add_route(action, options) # :nodoc:
1440
          path = path_for_action(action, options.delete(:path))
1441
          action = action.to_s.dup
1442

1443
          if action =~ /^[\w\-\/]+$/
1444
            options[:action] ||= action unless action.include?("/")
1445
          else
1446 1447 1448
            action = nil
          end

1449
          if !options.fetch(:as, true)
1450 1451 1452
            options.delete(:as)
          else
            options[:as] = name_for_action(options[:as], action)
J
Joshua Peek 已提交
1453
          end
J
Joshua Peek 已提交
1454

1455
          mapping = Mapping.new(@set, @scope, URI.parser.escape(path), options)
1456 1457
          app, conditions, requirements, defaults, as, anchor = mapping.to_route
          @set.add_route(app, conditions, requirements, defaults, as, anchor)
J
Joshua Peek 已提交
1458 1459
        end

1460 1461 1462 1463 1464 1465 1466 1467 1468
        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

1469
          if @scope[:scope_level] == :resources
1470 1471
            with_scope_level(:root) do
              scope(parent_resource.path) do
1472 1473 1474 1475 1476 1477
                super(options)
              end
            end
          else
            super(options)
          end
1478 1479
        end

1480
        protected
1481

1482
          def parent_resource #:nodoc:
1483 1484 1485
            @scope[:scope_level_resource]
          end

J
José Valim 已提交
1486
          def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
1487 1488 1489 1490 1491
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

1492 1493 1494 1495 1496
            if resource_scope?
              nested { send(method, resources.pop, options, &block) }
              return true
            end

1497
            options.keys.each do |k|
1498 1499 1500
              (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
            end

1501 1502 1503
            scope_options = options.slice!(*RESOURCE_OPTIONS)
            unless scope_options.empty?
              scope(scope_options) do
1504 1505 1506 1507 1508
                send(method, resources.pop, options, &block)
              end
              return true
            end

1509 1510 1511 1512
            unless action_options?(options)
              options.merge!(scope_action_options) if scope_action_options?
            end

1513 1514 1515
            false
          end

J
José Valim 已提交
1516
          def action_options?(options) #:nodoc:
1517 1518 1519
            options[:only] || options[:except]
          end

J
José Valim 已提交
1520
          def scope_action_options? #:nodoc:
A
Aaron Patterson 已提交
1521
            @scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
1522 1523
          end

J
José Valim 已提交
1524
          def scope_action_options #:nodoc:
1525 1526 1527
            @scope[:options].slice(:only, :except)
          end

J
José Valim 已提交
1528
          def resource_scope? #:nodoc:
1529
            RESOURCE_SCOPES.include? @scope[:scope_level]
1530 1531
          end

J
José Valim 已提交
1532
          def resource_method_scope? #:nodoc:
1533
            RESOURCE_METHOD_SCOPES.include? @scope[:scope_level]
1534 1535
          end

1536
          def with_exclusive_scope
1537
            begin
1538 1539
              old_name_prefix, old_path = @scope[:as], @scope[:path]
              @scope[:as], @scope[:path] = nil, nil
1540

1541 1542 1543
              with_scope_level(:exclusive) do
                yield
              end
1544
            ensure
1545
              @scope[:as], @scope[:path] = old_name_prefix, old_path
1546 1547 1548
            end
          end

1549
          def with_scope_level(kind, resource = parent_resource)
J
Joshua Peek 已提交
1550
            old, @scope[:scope_level] = @scope[:scope_level], kind
1551
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
J
Joshua Peek 已提交
1552 1553 1554
            yield
          ensure
            @scope[:scope_level] = old
1555
            @scope[:scope_level_resource] = old_resource
J
Joshua Peek 已提交
1556
          end
1557

1558 1559
          def resource_scope(kind, resource) #:nodoc:
            with_scope_level(kind, resource) do
1560
              scope(parent_resource.resource_scope) do
1561 1562 1563 1564 1565
                yield
              end
            end
          end

J
José Valim 已提交
1566
          def nested_options #:nodoc:
1567 1568
            options = { :as => parent_resource.member_name }
            options[:constraints] = {
1569 1570
              parent_resource.nested_param => param_constraint
            } if param_constraint?
1571 1572

            options
1573 1574
          end

1575 1576
          def param_constraint? #:nodoc:
            @scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp)
1577 1578
          end

1579 1580
          def param_constraint #:nodoc:
            @scope[:constraints][parent_resource.param]
1581 1582
          end

J
José Valim 已提交
1583
          def canonical_action?(action, flag) #:nodoc:
1584
            flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
1585 1586
          end

J
José Valim 已提交
1587
          def shallow_scoping? #:nodoc:
1588
            shallow? && @scope[:scope_level] == :member
1589 1590
          end

J
José Valim 已提交
1591
          def path_for_action(action, path) #:nodoc:
1592
            prefix = shallow_scoping? ?
1593
              "#{@scope[:shallow_path]}/#{parent_resource.shallow_scope}" : @scope[:path]
1594

1595
            if canonical_action?(action, path.blank?)
1596
              prefix.to_s
1597
            else
1598
              "#{prefix}/#{action_path(action, path)}"
1599 1600 1601
            end
          end

J
José Valim 已提交
1602
          def action_path(name, path = nil) #:nodoc:
1603
            name = name.to_sym if name.is_a?(String)
1604
            path || @scope[:path_names][name] || name.to_s
1605 1606
          end

J
José Valim 已提交
1607
          def prefix_name_for_action(as, action) #:nodoc:
1608
            if as
1609
              as.to_s
1610
            elsif !canonical_action?(action, @scope[:scope_level])
1611
              action.to_s
1612
            end
1613 1614
          end

J
José Valim 已提交
1615
          def name_for_action(as, action) #:nodoc:
1616
            prefix = prefix_name_for_action(as, action)
1617
            prefix = Mapper.normalize_name(prefix) if prefix
1618 1619 1620
            name_prefix = @scope[:as]

            if parent_resource
1621
              return nil unless as || action
1622

1623 1624
              collection_name = parent_resource.collection_name
              member_name = parent_resource.member_name
1625
            end
1626

1627
            name = case @scope[:scope_level]
1628
            when :nested
1629
              [name_prefix, prefix]
1630
            when :collection
1631
              [prefix, name_prefix, collection_name]
1632
            when :new
1633 1634 1635 1636 1637
              [prefix, :new, name_prefix, member_name]
            when :member
              [prefix, shallow_scoping? ? @scope[:shallow_prefix] : name_prefix, member_name]
            when :root
              [name_prefix, collection_name, prefix]
1638
            else
1639
              prefix.gsub!(/\-/, '_') if prefix.is_a?(String)
1640
              [name_prefix, member_name, prefix]
1641
            end
1642

1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
            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
1653
          end
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665

          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 已提交
1666
      end
J
Joshua Peek 已提交
1667

1668
      # Routing Concerns allow you to declare common routes that can be reused
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
      # 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
1688
      module Concerns
1689
        # Define a routing concern using a name.
1690
        #
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
        # 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]
1713 1714
        #   end
        #
1715 1716 1717
        # Or, using a callable object, you might implement something more
        # specific to your application, which would be out of place in your
        # routes file.
1718
        #
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
        #   # 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]
1730 1731 1732
        #     end
        #   end
        #
1733 1734 1735 1736 1737 1738 1739 1740
        #   # routes.rb
        #   concern :purchasable, Purchasable.new(returnable: true)
        #
        #   resources :toys, concerns: :purchasable
        #   resources :electronics, concerns: :purchasable
        #   resources :pets do
        #     concerns :purchasable, returnable: false
        #   end
1741
        #
1742 1743 1744
        # 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>.
1745
        def concern(name, callable = nil, &block)
1746 1747
          callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) }
          @concerns[name] = callable
1748 1749
        end

1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
        # 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
1761 1762 1763
        def concerns(*args)
          options = args.extract_options!
          args.flatten.each do |name|
1764
            if concern = @concerns[name]
1765
              concern.call(self, options)
1766 1767 1768 1769 1770 1771 1772
            else
              raise ArgumentError, "No concern named #{name} was found!"
            end
          end
        end
      end

1773 1774 1775
      def initialize(set) #:nodoc:
        @set = set
        @scope = { :path_names => @set.resources_path_names }
1776
        @concerns = {}
1777 1778
      end

1779 1780
      include Base
      include HttpHelpers
1781
      include Redirection
1782
      include Scoping
1783
      include Concerns
1784
      include Resources
J
Joshua Peek 已提交
1785 1786
    end
  end
J
Joshua Peek 已提交
1787
end