mapper.rb 51.4 KB
Newer Older
1
require 'active_support/core_ext/hash/except'
2
require 'active_support/core_ext/object/blank'
3
require 'active_support/inflector'
4
require 'action_dispatch/routing/redirection'
5

J
Joshua Peek 已提交
6 7
module ActionDispatch
  module Routing
J
Joshua Peek 已提交
8
    class Mapper
9
      class Constraints #:nodoc:
10
        def self.new(app, constraints, request = Rack::Request)
11
          if constraints.any?
12
            super(app, constraints, request)
13 14 15 16 17
          else
            app
          end
        end

18
        attr_reader :app, :constraints
19

20 21
        def initialize(app, constraints, request)
          @app, @constraints, @request = app, constraints, request
22 23
        end

24
        def matches?(env)
25
          req = @request.new(env)
26 27 28

          @constraints.each { |constraint|
            if constraint.respond_to?(:matches?) && !constraint.matches?(req)
29
              return false
30
            elsif constraint.respond_to?(:call) && !constraint.call(*constraint_args(constraint, req))
31
              return false
32 33 34
            end
          }

35 36 37 38 39
          return true
        end

        def call(env)
          matches?(env) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ]
40
        end
41 42 43 44 45

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

48
      class Mapping #:nodoc:
49
        IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix]
50
        ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
51
        SHORTHAND_REGEX = %r{/[\w/]+$}
52
        WILDCARD_PATH = %r{\*([^/\)]+)\)?$}
53

54
        def initialize(set, scope, path, options)
55
          @set, @scope = set, scope
56
          @segment_keys = nil
57
          @options = (@scope[:options] || {}).merge(options)
58
          @path = normalize_path(path)
59
          normalize_options!
60
        end
J
Joshua Peek 已提交
61

62
        def to_route
63
          [ app, conditions, requirements, defaults, @options[:as], @options[:anchor] ]
64
        end
J
Joshua Peek 已提交
65

66
        private
67 68 69

          def normalize_options!
            path_without_format = @path.sub(/\(\.:format\)$/, '')
70

71 72
            if using_match_shorthand?(path_without_format, @options)
              to_shorthand    = @options[:to].blank?
73
              @options[:to] ||= path_without_format.gsub(/\(.*\)/, "")[1..-1].sub(%r{/([^/]*)$}, '#\1')
74 75
            end

76
            @options.merge!(default_controller_and_action(to_shorthand))
77 78 79 80 81

            requirements.each do |name, requirement|
              # segment_keys.include?(k.to_s) || k == :controller
              next unless Regexp === requirement && !constraints[name]

82
              if requirement.source =~ ANCHOR_CHARACTERS_REGEX
83 84 85 86 87 88
                raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
              end
              if requirement.multiline?
                raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
              end
            end
89
          end
90

91
          # match "account/overview"
92
          def using_match_shorthand?(path, options)
93
            path && (options[:to] || options[:action]).nil? && path =~ SHORTHAND_REGEX
94
          end
95

96
          def normalize_path(path)
97 98
            raise ArgumentError, "path is required" if path.blank?
            path = Mapper.normalize_path(path)
99 100 101 102 103 104 105 106

            if path.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' }
107
              @options[:controller] ||= /.+?/
108 109
            end

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

116 117 118
            if @options[:format] == false
              @options.delete(:format)
              path
119
            elsif path.include?(":format") || path.end_with?('/')
120
              path
121 122
            elsif @options[:format] == true
              "#{path}.:format"
123 124 125
            else
              "#{path}(.:format)"
            end
126
          end
127

128 129
          def app
            Constraints.new(
130
              to.respond_to?(:call) ? to : Routing::RouteSet::Dispatcher.new(:defaults => defaults),
131 132
              blocks,
              @set.request_class
133
            )
134 135
          end

136 137 138
          def conditions
            { :path_info => @path }.merge(constraints).merge(request_method_condition)
          end
J
Joshua Peek 已提交
139

140
          def requirements
141
            @requirements ||= (@options[:constraints].is_a?(Hash) ? @options[:constraints] : {}).tap do |requirements|
142 143 144 145
              requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints]
              @options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) }
            end
          end
146

147
          def defaults
148 149 150 151 152 153
            @defaults ||= (@options[:defaults] || {}).tap do |defaults|
              defaults.reverse_merge!(@scope[:defaults]) if @scope[:defaults]
              @options.each { |k, v| defaults[k] = v unless v.is_a?(Regexp) || IGNORE_OPTIONS.include?(k.to_sym) }
            end
          end

154
          def default_controller_and_action(to_shorthand=nil)
155
            if to.respond_to?(:call)
156 157
              { }
            else
158
              if to.is_a?(String)
159
                controller, action = to.split('#')
160 161
              elsif to.is_a?(Symbol)
                action = to.to_s
162
              end
J
Joshua Peek 已提交
163

164 165
              controller ||= default_controller
              action     ||= default_action
166

167 168 169
              unless controller.is_a?(Regexp) || to_shorthand
                controller = [@scope[:module], controller].compact.join("/").presence
              end
170

171 172 173 174
              if controller.is_a?(String) && controller =~ %r{\A/}
                raise ArgumentError, "controller name should not start with a slash"
              end

175 176
              controller = controller.to_s unless controller.is_a?(Regexp)
              action     = action.to_s     unless action.is_a?(Regexp)
177

178
              if controller.blank? && segment_keys.exclude?("controller")
179 180
                raise ArgumentError, "missing :controller"
              end
J
Joshua Peek 已提交
181

182
              if action.blank? && segment_keys.exclude?("action")
183 184
                raise ArgumentError, "missing :action"
              end
J
Joshua Peek 已提交
185

A
Aaron Patterson 已提交
186
              hash = {}
A
Aaron Patterson 已提交
187 188
              hash[:controller] = controller unless controller.blank?
              hash[:action]     = action unless action.blank?
A
Aaron Patterson 已提交
189
              hash
190 191
            end
          end
192

193
          def blocks
194 195 196 197 198
            constraints = @options[:constraints]
            if constraints.present? && !constraints.is_a?(Hash)
              [constraints]
            else
              @scope[:blocks] || []
199 200
            end
          end
J
Joshua Peek 已提交
201

202 203 204
          def constraints
            @constraints ||= requirements.reject { |k, v| segment_keys.include?(k.to_s) || k == :controller }
          end
205

206 207
          def request_method_condition
            if via = @options[:via]
208 209
              list = Array(via).map { |m| m.to_s.dasherize.upcase }
              { :request_method => list }
210 211
            else
              { }
212
            end
213
          end
J
Joshua Peek 已提交
214

215
          def segment_keys
216 217 218
            return @segment_keys if @segment_keys

            @segment_keys = Journey::Path::Pattern.new(
219
              Journey::Router::Strexp.compile(@path, requirements, SEPARATORS)
220
            ).names
221
          end
222

223 224 225
          def to
            @options[:to]
          end
J
Joshua Peek 已提交
226

227
          def default_controller
228
            @options[:controller] || @scope[:controller]
229
          end
230 231

          def default_action
232
            @options[:action] || @scope[:action]
233
          end
234
      end
235

236
      # Invokes Rack::Mount::Utils.normalize path and ensure that
237 238
      # (:locale) becomes (/:locale) instead of /(:locale). Except
      # for root cases, where the latter is the correct one.
239
      def self.normalize_path(path)
240
        path = Journey::Router::Utils.normalize_path(path)
241
        path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^/]+\)$}
242 243 244
        path
      end

245 246 247 248
      def self.normalize_name(name)
        normalize_path(name)[1..-1].gsub("/", "_")
      end

249
      module Base
250 251 252 253
        # You can specify what Rails should route "/" to with the root method:
        #
        #   root :to => 'pages#main'
        #
254
        # For options, see +match+, as +root+ uses it internally.
255
        #
B
Brian Cardarella 已提交
256 257 258 259
        # You can also pass a string which will expand
        #
        #   root 'pages#main'
        #
260 261 262
        # 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.
263
        def root(options = {})
B
Brian Cardarella 已提交
264
          options = { :to => options } if options.is_a?(String)
265
          match '/', { :as => :root }.merge(options)
266
        end
267

268 269 270
        # 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:
271
        #
272
        #   # sets :controller, :action and :id in params
273
        #   match ':controller/:action/:id'
274
        #
275 276 277 278 279 280 281 282 283 284 285 286
        # 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:
        #
        #   match 'songs/*category/:title' => 'songs#show'
        #
        #   # '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:
287 288 289 290
        #
        #   match 'photos/:id' => 'photos#show'
        #   match 'photos/:id', :to => 'photos#show'
        #   match 'photos/:id', :controller => 'photos', :action => 'show'
291
        #
292 293 294
        # A pattern can also point to a +Rack+ endpoint i.e. anything that
        # responds to +call+:
        #
A
Alexey Vakhov 已提交
295
        #   match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon"] }
296 297 298 299
        #   match 'photos/:id' => PhotoRackApp
        #   # Yes, controller actions are just rack endpoints
        #   match 'photos/:id' => PhotosController.action(:show)
        #
300
        # === Options
301
        #
302
        # Any options not seen here are passed on as params with the url.
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
        #
        # [:controller]
        #   The route's controller.
        #
        # [:action]
        #   The route's action.
        #
        # [:path]
        #   The path prefix for the routes.
        #
        # [:module]
        #   The namespace for :controller.
        #
        #     match 'path' => 'c#a', :module => 'sekret', :controller => 'posts'
        #     #=> Sekret::PostsController
        #
        #   See <tt>Scoping#namespace</tt> for its scope equivalent.
        #
        # [:as]
        #   The name used to generate routing helpers.
        #
        # [:via]
        #   Allowed HTTP verb(s) for route.
        #
        #      match 'path' => 'c#a', :via => :get
        #      match 'path' => 'c#a', :via => [:get, :post]
        #
        # [:to]
331 332
        #   Points to a +Rack+ endpoint. Can be an object that responds to
        #   +call+ or a string representing a controller's action.
333
        #
334
        #      match 'path', :to => 'controller#action'
J
Justin Woodbridge 已提交
335
        #      match 'path', :to => lambda { |env| [200, {}, "Success!"] }
336
        #      match 'path', :to => RackApp
337 338 339
        #
        # [:on]
        #   Shorthand for wrapping routes in a specific RESTful context. Valid
340
        #   values are +:member+, +:collection+, and +:new+. Only use within
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
        #   <tt>resource(s)</tt> block. For example:
        #
        #      resource :bar do
        #        match 'foo' => 'c#a', :on => :member, :via => [:get, :post]
        #      end
        #
        #   Is equivalent to:
        #
        #      resource :bar do
        #        member do
        #          match 'foo' => 'c#a', :via => [:get, :post]
        #        end
        #      end
        #
        # [:constraints]
        #   Constrains parameters with a hash of regular expressions or an
357
        #   object that responds to <tt>matches?</tt>
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
        #
        #     match 'path/:id', :constraints => { :id => /[A-Z]\d{5}/ }
        #
        #     class Blacklist
        #       def matches?(request) request.remote_ip == '1.2.3.4' end
        #     end
        #     match 'path' => 'c#a', :constraints => Blacklist.new
        #
        #   See <tt>Scoping#constraints</tt> for more examples with its scope
        #   equivalent.
        #
        # [:defaults]
        #   Sets defaults for parameters
        #
        #     # Sets params[:format] to 'jpg' by default
        #     match 'path' => 'c#a', :defaults => { :format => 'jpg' }
        #
        #   See <tt>Scoping#defaults</tt> for its scope equivalent.
376 377
        #
        # [:anchor]
378
        #   Boolean to anchor a <tt>match</tt> pattern. Default is true. When set to
379 380 381 382
        #   false, the pattern matches any request prefixed with the given path.
        #
        #     # Matches any request starting with 'path'
        #     match 'path' => 'c#a', :anchor => false
383
        def match(path, options=nil)
384
        end
385

386 387
        # Mount a Rack-based application to be used within the application.
        #
R
Ryan Bigg 已提交
388
        #   mount SomeRackApp, :at => "some_route"
389 390 391
        #
        # Alternatively:
        #
R
Ryan Bigg 已提交
392
        #   mount(SomeRackApp => "some_route")
393
        #
394 395
        # For options, see +match+, as +mount+ uses it internally.
        #
396 397 398 399 400
        # 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:
        #
R
Ryan Bigg 已提交
401
        #   mount(SomeRackApp => "some_route", :as => "exciting")
402 403 404
        #
        # This will generate the +exciting_path+ and +exciting_url+ helpers
        # which can be used to navigate to this mounted app.
405 406 407 408 409 410 411 412 413 414 415
        def mount(app, options = nil)
          if options
            path = options.delete(:at)
          else
            options = app
            app, path = options.find { |k, v| k.respond_to?(:call) }
            options.delete(app) if app
          end

          raise "A rack application must be specified" unless path

416 417
          options[:as] ||= app_name(app)

418
          match(path, options.merge(:to => app, :anchor => false, :format => false))
419 420

          define_generate_prefix(app, options[:as])
421 422 423
          self
        end

424 425 426 427
        def default_url_options=(options)
          @set.default_url_options = options
        end
        alias_method :default_url_options, :default_url_options=
428

429 430 431 432 433 434
        def with_default_scope(scope, &block)
          scope(scope) do
            instance_exec(&block)
          end
        end

435 436 437
        private
          def app_name(app)
            return unless app.respond_to?(:routes)
438 439 440 441 442 443 444

            if app.respond_to?(:railtie_name)
              app.railtie_name
            else
              class_name = app.class.is_a?(Class) ? app.name : app.class.name
              ActiveSupport::Inflector.underscore(class_name).gsub("/", "_")
            end
445 446 447
          end

          def define_generate_prefix(app, name)
448
            return unless app.respond_to?(:routes) && app.routes.respond_to?(:define_mounted_helper)
449 450

            _route = @set.named_routes.routes[name.to_sym]
P
Piotr Sarnacki 已提交
451 452
            _routes = @set
            app.routes.define_mounted_helper(name)
J
José Valim 已提交
453 454 455 456 457
            app.routes.singleton_class.class_eval do
              define_method :mounted? do
                true
              end

458
              define_method :_generate_prefix do |options|
P
Piotr Sarnacki 已提交
459
                prefix_options = options.slice(*_route.segment_keys)
460 461
                # we must actually delete prefix segment keys to avoid passing them to next url_for
                _route.segment_keys.each { |k| options.delete(k) }
R
rails-noob 已提交
462 463 464
                prefix = _routes.url_helpers.send("#{name}_path", prefix_options)
                prefix = '' if prefix == '/'
                prefix
465 466 467
              end
            end
          end
468 469 470
      end

      module HttpHelpers
471
        # Define a route that only recognizes HTTP GET.
472
        # For supported arguments, see <tt>Base#match</tt>.
473 474 475
        #
        # Example:
        #
476
        #   get 'bacon', :to => 'food#bacon'
477
        def get(*args, &block)
478
          map_method(:get, args, &block)
479 480
        end

481
        # Define a route that only recognizes HTTP POST.
482
        # For supported arguments, see <tt>Base#match</tt>.
483 484 485
        #
        # Example:
        #
486
        #   post 'bacon', :to => 'food#bacon'
487
        def post(*args, &block)
488
          map_method(:post, args, &block)
489 490
        end

491 492 493 494 495 496 497 498 499 500
        # Define a route that only recognizes HTTP PATCH.
        # For supported arguments, see <tt>Base#match</tt>.
        #
        # Example:
        #
        #   patch 'bacon', :to => 'food#bacon'
        def patch(*args, &block)
          map_method(:patch, args, &block)
        end

501
        # Define a route that only recognizes HTTP PUT.
502
        # For supported arguments, see <tt>Base#match</tt>.
503 504 505
        #
        # Example:
        #
506
        #   put 'bacon', :to => 'food#bacon'
507
        def put(*args, &block)
508
          map_method(:put, args, &block)
509 510
        end

511
        # Define a route that only recognizes HTTP DELETE.
512
        # For supported arguments, see <tt>Base#match</tt>.
513 514 515
        #
        # Example:
        #
516
        #   delete 'broccoli', :to => 'food#broccoli'
517
        def delete(*args, &block)
518
          map_method(:delete, args, &block)
519 520 521
        end

        private
522
          def map_method(method, args, &block)
523 524
            options = args.extract_options!
            options[:via] = method
525
            match(*args, options, &block)
526 527 528 529
            self
          end
      end

530 531 532
      # 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 已提交
533 534
      # the <tt>app/controllers/admin</tt> directory, and you can group them
      # together in your router:
535 536 537 538
      #
      #   namespace "admin" do
      #     resources :posts, :comments
      #   end
539
      #
540
      # This will create a number of routes for each of the posts and comments
S
Sebastian Martinez 已提交
541
      # controller. For <tt>Admin::PostsController</tt>, Rails will create:
542
      #
543 544 545 546 547
      #   GET       /admin/posts
      #   GET       /admin/posts/new
      #   POST      /admin/posts
      #   GET       /admin/posts/1
      #   GET       /admin/posts/1/edit
548
      #   PATCH/PUT /admin/posts/1
549
      #   DELETE    /admin/posts/1
550
      #
551
      # If you want to route /posts (without the prefix /admin) to
S
Sebastian Martinez 已提交
552
      # <tt>Admin::PostsController</tt>, you could use
553
      #
554
      #   scope :module => "admin" do
555
      #     resources :posts
556 557 558
      #   end
      #
      # or, for a single case
559
      #
560
      #   resources :posts, :module => "admin"
561
      #
S
Sebastian Martinez 已提交
562
      # If you want to route /admin/posts to +PostsController+
563
      # (without the Admin:: module prefix), you could use
564
      #
565
      #   scope "/admin" do
566
      #     resources :posts
567 568 569
      #   end
      #
      # or, for a single case
570
      #
571
      #   resources :posts, :path => "/admin/posts"
572 573 574
      #
      # 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 已提交
575
      # +PostsController+:
576
      #
577 578 579 580 581
      #   GET       /admin/posts
      #   GET       /admin/posts/new
      #   POST      /admin/posts
      #   GET       /admin/posts/1
      #   GET       /admin/posts/1/edit
582
      #   PATCH/PUT /admin/posts/1
583
      #   DELETE    /admin/posts/1
584
      module Scoping
585
        # Scopes a set of routes to the given default options.
586 587 588 589 590 591 592 593
        #
        # Take the following route definition as an example:
        #
        #   scope :path => ":account_id", :as => "account" do
        #     resources :projects
        #   end
        #
        # This generates helpers such as +account_projects_path+, just like +resources+ does.
594 595
        # The difference here being that the routes generated are like /:account_id/projects,
        # rather than /accounts/:account_id/projects.
596
        #
597
        # === Options
598
        #
599
        # Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>.
600
        #
601
        # === Examples
602
        #
S
Sebastian Martinez 已提交
603
        #   # route /posts (without the prefix /admin) to <tt>Admin::PostsController</tt>
604 605 606
        #   scope :module => "admin" do
        #     resources :posts
        #   end
607
        #
608 609 610 611
        #   # prefix the posts resource's requests with '/admin'
        #   scope :path => "/admin" do
        #     resources :posts
        #   end
612
        #
S
Sebastian Martinez 已提交
613
        #   # prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+
614 615 616
        #   scope :as => "sekret" do
        #     resources :posts
        #   end
617 618
        def scope(*args)
          options = args.extract_options!
619
          options = options.dup
620

621
          options[:path] = args.first if args.first.is_a?(String)
622
          recover = {}
623

624 625
          options[:constraints] ||= {}
          unless options[:constraints].is_a?(Hash)
626
            block, options[:constraints] = options[:constraints], {}
627
          end
628

629 630 631 632 633
          scope_options.each do |option|
            if value = options.delete(option)
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
634 635
          end

636 637 638 639 640 641
          recover[:block] = @scope[:blocks]
          @scope[:blocks] = merge_blocks_scope(@scope[:blocks], block)

          recover[:options] = @scope[:options]
          @scope[:options]  = merge_options_scope(@scope[:options], options)

642 643 644
          yield
          self
        ensure
645 646 647
          scope_options.each do |option|
            @scope[option] = recover[option] if recover.has_key?(option)
          end
648 649 650

          @scope[:options] = recover[:options]
          @scope[:blocks]  = recover[:block]
651 652
        end

653 654 655 656 657 658
        # Scopes routes to a specific controller
        #
        # Example:
        #   controller "food" do
        #     match "bacon", :action => "bacon"
        #   end
659 660 661
        def controller(controller, options={})
          options[:controller] = controller
          scope(options) { yield }
662 663
        end

664 665 666 667 668 669 670 671
        # Scopes routes to a specific namespace. For example:
        #
        #   namespace :admin do
        #     resources :posts
        #   end
        #
        # This generates the following routes:
        #
672 673 674 675 676
        #       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
677
        #        admin_post PATCH/PUT /admin/posts/:id(.:format)      admin/posts#update
678
        #        admin_post DELETE    /admin/posts/:id(.:format)      admin/posts#destroy
679
        #
680
        # === Options
681
        #
682 683
        # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
        # options all default to the name of the namespace.
684
        #
685 686
        # For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
        # <tt>Resources#resources</tt>.
687
        #
688
        # === Examples
689
        #
690 691 692 693
        #   # accessible through /sekret/posts rather than /admin/posts
        #   namespace :admin, :path => "sekret" do
        #     resources :posts
        #   end
694
        #
S
Sebastian Martinez 已提交
695
        #   # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
696 697 698
        #   namespace :admin, :module => "sekret" do
        #     resources :posts
        #   end
699
        #
S
Sebastian Martinez 已提交
700
        #   # generates +sekret_posts_path+ rather than +admin_posts_path+
701 702 703
        #   namespace :admin, :as => "sekret" do
        #     resources :posts
        #   end
704
        def namespace(path, options = {})
705
          path = path.to_s
706 707 708
          options = { :path => path, :as => path, :module => path,
                      :shallow_path => path, :shallow_prefix => path }.merge!(options)
          scope(options) { yield }
709
        end
710

R
Ryan Bigg 已提交
711 712 713 714
        # === 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:
        #
M
mjy 已提交
715
        #   constraints(:id => /\d+\.\d+/) do
R
Ryan Bigg 已提交
716 717 718 719 720
        #     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.
721
        #
R
R.T. Lechow 已提交
722
        # You may use this to also restrict other parameters:
R
Ryan Bigg 已提交
723 724
        #
        #   resources :posts do
M
mjy 已提交
725
        #     constraints(:post_id => /\d+\.\d+/) do
R
Ryan Bigg 已提交
726 727
        #       resources :comments
        #     end
J
James Miller 已提交
728
        #   end
R
Ryan Bigg 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741 742
        #
        # === Restricting based on IP
        #
        # Routes can also be constrained to an IP or a certain range of IP addresses:
        #
        #   constraints(:ip => /192.168.\d+.\d+/) do
        #     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 已提交
743
        # Requests to routes can be constrained based on specific criteria:
R
Ryan Bigg 已提交
744 745 746 747 748 749 750 751 752 753
        #
        #    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
754
        #      def self.matches?(request)
R
Ryan Bigg 已提交
755 756 757 758 759 760 761 762 763 764 765
        #        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
766 767 768 769
        def constraints(constraints = {})
          scope(:constraints => constraints) { yield }
        end

R
Ryan Bigg 已提交
770
        # Allows you to set default parameters for a route, such as this:
771 772 773
        #   defaults :id => 'home' do
        #     match 'scoped_pages/(:id)', :to => 'pages#show'
        #   end
R
Ryan Bigg 已提交
774
        # Using this, the +:id+ parameter here will default to 'home'.
775 776 777 778
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

779
        private
J
José Valim 已提交
780
          def scope_options #:nodoc:
781 782 783
            @scope_options ||= private_methods.grep(/^merge_(.+)_scope$/) { $1.to_sym }
          end

J
José Valim 已提交
784
          def merge_path_scope(parent, child) #:nodoc:
785
            Mapper.normalize_path("#{parent}/#{child}")
786 787
          end

J
José Valim 已提交
788
          def merge_shallow_path_scope(parent, child) #:nodoc:
789 790 791
            Mapper.normalize_path("#{parent}/#{child}")
          end

J
José Valim 已提交
792
          def merge_as_scope(parent, child) #:nodoc:
793
            parent ? "#{parent}_#{child}" : child
794 795
          end

J
José Valim 已提交
796
          def merge_shallow_prefix_scope(parent, child) #:nodoc:
797 798 799
            parent ? "#{parent}_#{child}" : child
          end

J
José Valim 已提交
800
          def merge_module_scope(parent, child) #:nodoc:
801 802 803
            parent ? "#{parent}/#{child}" : child
          end

J
José Valim 已提交
804
          def merge_controller_scope(parent, child) #:nodoc:
805
            child
806 807
          end

J
José Valim 已提交
808
          def merge_path_names_scope(parent, child) #:nodoc:
809 810 811
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
812
          def merge_constraints_scope(parent, child) #:nodoc:
813 814 815
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
816
          def merge_defaults_scope(parent, child) #:nodoc:
817 818 819
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
820
          def merge_blocks_scope(parent, child) #:nodoc:
821 822 823
            merged = parent ? parent.dup : []
            merged << child if child
            merged
824 825
          end

J
José Valim 已提交
826
          def merge_options_scope(parent, child) #:nodoc:
827
            (parent || {}).except(*override_keys(child)).merge(child)
828
          end
829

J
José Valim 已提交
830
          def merge_shallow_scope(parent, child) #:nodoc:
831 832
            child ? true : false
          end
833

J
José Valim 已提交
834
          def override_keys(child) #:nodoc:
835 836
            child.key?(:only) || child.key?(:except) ? [:only, :except] : []
          end
837 838
      end

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
      # 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 已提交
863 864
      # <tt>app/controllers/admin</tt> directory, and you can group them together
      # in your router:
865 866 867 868 869
      #
      #   namespace "admin" do
      #     resources :posts, :comments
      #   end
      #
S
Sebastian Martinez 已提交
870 871
      # 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
872 873 874 875
      # overrides this restriction, e.g:
      #
      #   resources :articles, :id => /[^\/]+/
      #
S
Sebastian Martinez 已提交
876
      # This allows any character other than a slash as part of your +:id+.
877
      #
J
Joshua Peek 已提交
878
      module Resources
879 880
        # CANONICAL_ACTIONS holds all actions that does not need a prefix or
        # a path appended since they fit properly in their scope level.
881 882 883
        VALID_ON_OPTIONS  = [:new, :collection, :member]
        RESOURCE_OPTIONS  = [:as, :controller, :path, :only, :except]
        CANONICAL_ACTIONS = %w(index create new show update destroy)
884

885
        class Resource #:nodoc:
886
          attr_reader :controller, :path, :options
887 888

          def initialize(entities, options = {})
889
            @name       = entities.to_s
890 891 892
            @path       = (options[:path] || @name).to_s
            @controller = (options[:controller] || @name).to_s
            @as         = options[:as]
893
            @options    = options
894 895
          end

896
          def default_actions
897
            [:index, :create, :new, :show, :update, :destroy, :edit]
898 899
          end

900
          def actions
901
            if only = @options[:only]
902
              Array(only).map(&:to_sym)
903
            elsif except = @options[:except]
904 905 906 907 908 909
              default_actions - Array(except).map(&:to_sym)
            else
              default_actions
            end
          end

910
          def name
911
            @as || @name
912 913
          end

914
          def plural
915
            @plural ||= name.to_s
916 917 918
          end

          def singular
919
            @singular ||= name.to_s.singularize
920 921
          end

922
          alias :member_name :singular
923

924
          # Checks for uncountable plurals, and appends "_index" if the plural
925
          # and singular form are the same.
926
          def collection_name
927
            singular == plural ? "#{plural}_index" : plural
928 929
          end

930
          def resource_scope
931
            { :controller => controller }
932 933
          end

934
          alias :collection_scope :path
935 936

          def member_scope
937
            "#{path}/:id"
938 939
          end

940
          def new_scope(new_path)
941
            "#{path}/#{new_path}"
942 943 944
          end

          def nested_scope
945
            "#{path}/:#{singular}_id"
946
          end
947

948 949 950
        end

        class SingletonResource < Resource #:nodoc:
951
          def initialize(entities, options)
952
            super
953
            @as         = nil
954 955
            @controller = (options[:controller] || plural).to_s
            @as         = options[:as]
956 957
          end

958 959 960 961
          def default_actions
            [:show, :create, :update, :destroy, :new, :edit]
          end

962 963
          def plural
            @plural ||= name.to_s.pluralize
964 965
          end

966 967
          def singular
            @singular ||= name.to_s
968
          end
969 970 971 972 973 974

          alias :member_name :singular
          alias :collection_name :singular

          alias :member_scope :path
          alias :nested_scope :path
975 976
        end

977 978 979 980
        def resources_path_names(options)
          @scope[:path_names].merge!(options)
        end

981 982 983 984 985 986 987 988 989
        # 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 :geocoder
        #
        # creates six different routes in your application, all mapping to
S
Sebastian Martinez 已提交
990
        # the +GeoCoders+ controller (note that the controller is named after
991 992
        # the plural):
        #
993 994 995 996
        #   GET       /geocoder/new
        #   POST      /geocoder
        #   GET       /geocoder
        #   GET       /geocoder/edit
997
        #   PATCH/PUT /geocoder
998
        #   DELETE    /geocoder
999
        #
1000
        # === Options
1001
        # Takes same options as +resources+.
J
Joshua Peek 已提交
1002
        def resource(*resources, &block)
J
Joshua Peek 已提交
1003
          options = resources.extract_options!
J
Joshua Peek 已提交
1004

1005
          if apply_common_behavior_for(:resource, resources, options, &block)
1006 1007 1008
            return self
          end

1009
          resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
1010
            yield if block_given?
1011

1012
            collection do
1013
              post :create
1014
            end if parent_resource.actions.include?(:create)
1015

1016
            new do
1017
              get :new
1018
            end if parent_resource.actions.include?(:new)
1019

1020
            member do
1021 1022
              get :edit if parent_resource.actions.include?(:edit)
              get :show if parent_resource.actions.include?(:show)
1023
              if parent_resource.actions.include?(:update)
1024 1025
                patch :update
                put   :update
1026
              end
1027
              delete :destroy if parent_resource.actions.include?(:destroy)
1028 1029 1030
            end
          end

J
Joshua Peek 已提交
1031
          self
1032 1033
        end

1034 1035 1036 1037 1038 1039 1040 1041
        # 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 已提交
1042
        # the +Photos+ controller:
1043
        #
1044 1045 1046 1047 1048
        #   GET       /photos
        #   GET       /photos/new
        #   POST      /photos
        #   GET       /photos/:id
        #   GET       /photos/:id/edit
1049
        #   PATCH/PUT /photos/:id
1050
        #   DELETE    /photos/:id
1051
        #
1052 1053 1054 1055 1056 1057 1058 1059
        # Resources can also be nested infinitely by using this block syntax:
        #
        #   resources :photos do
        #     resources :comments
        #   end
        #
        # This generates the following comments routes:
        #
1060 1061 1062 1063 1064
        #   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
1065
        #   PATCH/PUT /photos/:photo_id/comments/:id
1066
        #   DELETE    /photos/:photo_id/comments/:id
1067
        #
1068
        # === Options
1069 1070
        # Takes same options as <tt>Base#match</tt> as well as:
        #
1071
        # [:path_names]
A
Aviv Ben-Yosef 已提交
1072 1073
        #   Allows you to change the segment component of the +edit+ and +new+ actions.
        #   Actions not specified are not changed.
1074 1075 1076 1077
        #
        #     resources :posts, :path_names => { :new => "brand_new" }
        #
        #   The above example will now change /posts/new to /posts/brand_new
1078
        #
1079 1080 1081 1082 1083 1084 1085
        # [:path]
        #   Allows you to change the path prefix for the resource.
        #
        #     resources :posts, :path => 'postings'
        #
        #   The resource and all segments will now route to /postings instead of /posts
        #
1086 1087
        # [:only]
        #   Only generate routes for the given actions.
1088
        #
1089 1090
        #     resources :cows, :only => :show
        #     resources :cows, :only => [:show, :index]
1091
        #
1092 1093
        # [:except]
        #   Generate all routes except for the given actions.
1094
        #
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
        #     resources :cows, :except => :show
        #     resources :cows, :except => [:show, :index]
        #
        # [:shallow]
        #   Generates shallow routes for nested resource(s). When placed on a parent resource,
        #   generates shallow routes for all nested resources.
        #
        #     resources :posts, :shallow => true do
        #       resources :comments
        #     end
        #
        #   Is the same as:
        #
        #     resources :posts do
1109
        #       resources :comments, :except => [:show, :edit, :update, :destroy]
1110
        #     end
1111 1112 1113 1114 1115
        #     resources :comments, :only => [:show, :edit, :update, :destroy]
        #
        #   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>.
1116 1117 1118 1119
        #
        # [:shallow_path]
        #   Prefixes nested shallow routes with the specified path.
        #
1120 1121 1122 1123
        #     scope :shallow_path => "sekret" do
        #       resources :posts do
        #         resources :comments, :shallow => true
        #       end
1124 1125 1126 1127
        #     end
        #
        #   The +comments+ resource here will have the following routes generated for it:
        #
1128 1129 1130 1131 1132
        #     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)
1133
        #     comment          PATCH/PUT /sekret/comments/:id(.:format)
1134
        #     comment          DELETE    /sekret/comments/:id(.:format)
1135 1136
        #
        # === Examples
1137
        #
S
Sebastian Martinez 已提交
1138
        #   # routes call <tt>Admin::PostsController</tt>
1139
        #   resources :posts, :module => "admin"
1140
        #
1141
        #   # resource actions are at /admin/posts.
1142
        #   resources :posts, :path => "admin/posts"
J
Joshua Peek 已提交
1143
        def resources(*resources, &block)
J
Joshua Peek 已提交
1144
          options = resources.extract_options!
1145

1146
          if apply_common_behavior_for(:resources, resources, options, &block)
1147 1148 1149
            return self
          end

1150
          resource_scope(:resources, Resource.new(resources.pop, options)) do
1151
            yield if block_given?
J
Joshua Peek 已提交
1152

1153
            collection do
1154 1155
              get  :index if parent_resource.actions.include?(:index)
              post :create if parent_resource.actions.include?(:create)
1156
            end
1157

1158
            new do
1159
              get :new
1160
            end if parent_resource.actions.include?(:new)
1161

1162
            member do
1163 1164
              get :edit if parent_resource.actions.include?(:edit)
              get :show if parent_resource.actions.include?(:show)
1165
              if parent_resource.actions.include?(:update)
1166 1167
                patch :update
                put   :update
1168
              end
1169
              delete :destroy if parent_resource.actions.include?(:destroy)
1170 1171 1172
            end
          end

J
Joshua Peek 已提交
1173
          self
1174 1175
        end

1176 1177 1178 1179 1180 1181 1182 1183 1184
        # 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 已提交
1185
        # with GET, and route to the search action of +PhotosController+. It will also
1186 1187
        # create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
        # route helpers.
J
Joshua Peek 已提交
1188
        def collection
1189 1190
          unless resource_scope?
            raise ArgumentError, "can't use collection outside resource(s) scope"
1191 1192
          end

1193 1194 1195 1196
          with_scope_level(:collection) do
            scope(parent_resource.collection_scope) do
              yield
            end
J
Joshua Peek 已提交
1197
          end
1198
        end
J
Joshua Peek 已提交
1199

1200 1201 1202 1203 1204 1205 1206 1207 1208
        # 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 已提交
1209
        # preview action of +PhotosController+. It will also create the
1210
        # <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
J
Joshua Peek 已提交
1211
        def member
1212 1213
          unless resource_scope?
            raise ArgumentError, "can't use member outside resource(s) scope"
J
Joshua Peek 已提交
1214
          end
J
Joshua Peek 已提交
1215

1216 1217 1218 1219
          with_scope_level(:member) do
            scope(parent_resource.member_scope) do
              yield
            end
1220 1221 1222 1223 1224 1225 1226
          end
        end

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

1228 1229 1230 1231
          with_scope_level(:new) do
            scope(parent_resource.new_scope(action_path(:new))) do
              yield
            end
J
Joshua Peek 已提交
1232
          end
J
Joshua Peek 已提交
1233 1234
        end

1235
        def nested
1236 1237
          unless resource_scope?
            raise ArgumentError, "can't use nested outside resource(s) scope"
1238 1239 1240
          end

          with_scope_level(:nested) do
1241
            if shallow?
1242
              with_exclusive_scope do
1243
                if @scope[:shallow_path].blank?
1244
                  scope(parent_resource.nested_scope, nested_options) { yield }
1245
                else
1246
                  scope(@scope[:shallow_path], :as => @scope[:shallow_prefix]) do
1247
                    scope(parent_resource.nested_scope, nested_options) { yield }
1248 1249 1250 1251
                  end
                end
              end
            else
1252
              scope(parent_resource.nested_scope, nested_options) { yield }
1253 1254 1255 1256
            end
          end
        end

1257
        # See ActionDispatch::Routing::Mapper::Scoping#namespace
1258
        def namespace(path, options = {})
1259
          if resource_scope?
1260 1261 1262 1263 1264 1265
            nested { super }
          else
            super
          end
        end

1266
        def shallow
1267
          scope(:shallow => true, :shallow_path => @scope[:path]) do
1268 1269 1270 1271
            yield
          end
        end

1272 1273 1274 1275
        def shallow?
          parent_resource.instance_of?(Resource) && @scope[:shallow]
        end

1276
        # match 'path' => 'controller#action'
R
Rafael Mendonça França 已提交
1277
        # match 'path', to: 'controller#action'
1278
        # match 'path', 'otherpath', on: :member, via: :get
1279 1280 1281 1282
        def match(path, *rest)
          if rest.empty? && Hash === path
            options  = path
            path, to = options.find { |name, value| name.is_a?(String) }
1283 1284
            options[:to] = to
            options.delete(path)
1285 1286 1287 1288 1289 1290
            paths = [path]
          else
            options = rest.pop || {}
            paths = [path] + rest
          end

1291 1292
          options[:anchor] = true unless options.key?(:anchor)

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

1297
          paths.each { |_path| decomposed_match(_path, options.dup) }
1298 1299
          self
        end
1300

1301
        def decomposed_match(path, options) # :nodoc:
A
Aaron Patterson 已提交
1302 1303
          if on = options.delete(:on)
            send(on) { decomposed_match(path, options) }
1304
          else
A
Aaron Patterson 已提交
1305 1306 1307 1308 1309 1310 1311 1312
            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 已提交
1313
          end
1314
        end
J
Joshua Peek 已提交
1315

1316
        def add_route(action, options) # :nodoc:
1317
          path = path_for_action(action, options.delete(:path))
1318

1319 1320 1321
          if action.to_s =~ /^[\w\/]+$/
            options[:action] ||= action unless action.to_s.include?("/")
          else
1322 1323 1324
            action = nil
          end

1325
          if !options.fetch(:as, true)
1326 1327 1328
            options.delete(:as)
          else
            options[:as] = name_for_action(options[:as], action)
J
Joshua Peek 已提交
1329
          end
J
Joshua Peek 已提交
1330

1331 1332 1333
          mapping = Mapping.new(@set, @scope, path, options)
          app, conditions, requirements, defaults, as, anchor = mapping.to_route
          @set.add_route(app, conditions, requirements, defaults, as, anchor)
J
Joshua Peek 已提交
1334 1335
        end

1336
        def root(options={})
1337
          if @scope[:scope_level] == :resources
1338 1339
            with_scope_level(:root) do
              scope(parent_resource.path) do
1340 1341 1342 1343 1344 1345
                super(options)
              end
            end
          else
            super(options)
          end
1346 1347
        end

1348
        protected
1349

1350
          def parent_resource #:nodoc:
1351 1352 1353
            @scope[:scope_level_resource]
          end

J
José Valim 已提交
1354
          def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
1355 1356 1357 1358 1359
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

1360 1361 1362 1363 1364
            if resource_scope?
              nested { send(method, resources.pop, options, &block) }
              return true
            end

1365
            options.keys.each do |k|
1366 1367 1368
              (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
            end

1369 1370 1371
            scope_options = options.slice!(*RESOURCE_OPTIONS)
            unless scope_options.empty?
              scope(scope_options) do
1372 1373 1374 1375 1376
                send(method, resources.pop, options, &block)
              end
              return true
            end

1377 1378 1379 1380
            unless action_options?(options)
              options.merge!(scope_action_options) if scope_action_options?
            end

1381 1382 1383
            false
          end

J
José Valim 已提交
1384
          def action_options?(options) #:nodoc:
1385 1386 1387
            options[:only] || options[:except]
          end

J
José Valim 已提交
1388
          def scope_action_options? #:nodoc:
A
Aaron Patterson 已提交
1389
            @scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
1390 1391
          end

J
José Valim 已提交
1392
          def scope_action_options #:nodoc:
1393 1394 1395
            @scope[:options].slice(:only, :except)
          end

J
José Valim 已提交
1396
          def resource_scope? #:nodoc:
1397
            [:resource, :resources].include? @scope[:scope_level]
1398 1399
          end

J
José Valim 已提交
1400
          def resource_method_scope? #:nodoc:
1401
            [:collection, :member, :new].include? @scope[:scope_level]
1402 1403
          end

1404
          def with_exclusive_scope
1405
            begin
1406 1407
              old_name_prefix, old_path = @scope[:as], @scope[:path]
              @scope[:as], @scope[:path] = nil, nil
1408

1409 1410 1411
              with_scope_level(:exclusive) do
                yield
              end
1412
            ensure
1413
              @scope[:as], @scope[:path] = old_name_prefix, old_path
1414 1415 1416
            end
          end

1417
          def with_scope_level(kind, resource = parent_resource)
J
Joshua Peek 已提交
1418
            old, @scope[:scope_level] = @scope[:scope_level], kind
1419
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
J
Joshua Peek 已提交
1420 1421 1422
            yield
          ensure
            @scope[:scope_level] = old
1423
            @scope[:scope_level_resource] = old_resource
J
Joshua Peek 已提交
1424
          end
1425

1426 1427
          def resource_scope(kind, resource) #:nodoc:
            with_scope_level(kind, resource) do
1428
              scope(parent_resource.resource_scope) do
1429 1430 1431 1432 1433
                yield
              end
            end
          end

J
José Valim 已提交
1434
          def nested_options #:nodoc:
1435 1436 1437 1438 1439 1440
            options = { :as => parent_resource.member_name }
            options[:constraints] = {
              :"#{parent_resource.singular}_id" => id_constraint
            } if id_constraint?

            options
1441 1442
          end

J
José Valim 已提交
1443
          def id_constraint? #:nodoc:
1444
            @scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp)
1445 1446
          end

J
José Valim 已提交
1447
          def id_constraint #:nodoc:
1448
            @scope[:constraints][:id]
1449 1450
          end

J
José Valim 已提交
1451
          def canonical_action?(action, flag) #:nodoc:
1452
            flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
1453 1454
          end

J
José Valim 已提交
1455
          def shallow_scoping? #:nodoc:
1456
            shallow? && @scope[:scope_level] == :member
1457 1458
          end

J
José Valim 已提交
1459
          def path_for_action(action, path) #:nodoc:
1460
            prefix = shallow_scoping? ?
1461 1462
              "#{@scope[:shallow_path]}/#{parent_resource.path}/:id" : @scope[:path]

1463 1464
            path = if canonical_action?(action, path.blank?)
              prefix.to_s
1465
            else
1466
              "#{prefix}/#{action_path(action, path)}"
1467 1468 1469
            end
          end

J
José Valim 已提交
1470
          def action_path(name, path = nil) #:nodoc:
1471
            name = name.to_sym if name.is_a?(String)
1472
            path || @scope[:path_names][name] || name.to_s
1473 1474
          end

J
José Valim 已提交
1475
          def prefix_name_for_action(as, action) #:nodoc:
1476
            if as
1477
              as.to_s
1478
            elsif !canonical_action?(action, @scope[:scope_level])
1479
              action.to_s
1480
            end
1481 1482
          end

J
José Valim 已提交
1483
          def name_for_action(as, action) #:nodoc:
1484
            prefix = prefix_name_for_action(as, action)
1485
            prefix = Mapper.normalize_name(prefix) if prefix
1486 1487 1488
            name_prefix = @scope[:as]

            if parent_resource
1489
              return nil unless as || action
1490

1491 1492
              collection_name = parent_resource.collection_name
              member_name = parent_resource.member_name
1493
            end
1494

1495
            name = case @scope[:scope_level]
1496
            when :nested
1497
              [name_prefix, prefix]
1498
            when :collection
1499
              [prefix, name_prefix, collection_name]
1500
            when :new
1501 1502 1503 1504 1505
              [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]
1506
            else
1507
              [name_prefix, member_name, prefix]
1508
            end
1509

1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
            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
1520
          end
J
Joshua Peek 已提交
1521
      end
J
Joshua Peek 已提交
1522

1523 1524 1525 1526 1527
      def initialize(set) #:nodoc:
        @set = set
        @scope = { :path_names => @set.resources_path_names }
      end

1528 1529
      include Base
      include HttpHelpers
1530
      include Redirection
1531 1532
      include Scoping
      include Resources
J
Joshua Peek 已提交
1533 1534
    end
  end
J
Joshua Peek 已提交
1535
end