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

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

19 20
        attr_reader :app

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

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

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

36 37 38 39 40
          return true
        end

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

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

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

55
        def initialize(set, scope, path, options)
56 57
          @set, @scope = set, scope
          @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
            @segment_keys ||= Journey::Path::Pattern.new(
              Journey::Router::Strexp.compile(@path, requirements, SEPARATORS)
218
            ).names
219
          end
220

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

225
          def default_controller
226
            @options[:controller] || @scope[:controller]
227
          end
228 229

          def default_action
230
            @options[:action] || @scope[:action]
231
          end
232
      end
233

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

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

247
      module Base
248 249 250 251
        # You can specify what Rails should route "/" to with the root method:
        #
        #   root :to => 'pages#main'
        #
252
        # For options, see +match+, as +root+ uses it internally.
253
        #
254 255 256
        # 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.
257
        def root(options = {})
258
          match '/', { :as => :root }.merge(options)
259
        end
260

261 262 263
        # 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:
264
        #
265
        #   # sets :controller, :action and :id in params
266
        #   match ':controller/:action/:id'
267
        #
268 269 270 271 272 273 274 275 276 277 278 279
        # 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:
280 281 282 283
        #
        #   match 'photos/:id' => 'photos#show'
        #   match 'photos/:id', :to => 'photos#show'
        #   match 'photos/:id', :controller => 'photos', :action => 'show'
284
        #
285 286 287 288 289 290 291 292
        # A pattern can also point to a +Rack+ endpoint i.e. anything that
        # responds to +call+:
        #
        #   match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon" }
        #   match 'photos/:id' => PhotoRackApp
        #   # Yes, controller actions are just rack endpoints
        #   match 'photos/:id' => PhotosController.action(:show)
        #
293
        # === Options
294
        #
295
        # Any options not seen here are passed on as params with the url.
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        #
        # [: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]
324 325
        #   Points to a +Rack+ endpoint. Can be an object that responds to
        #   +call+ or a string representing a controller's action.
326
        #
327 328 329
        #      match 'path', :to => 'controller#action'
        #      match 'path', :to => lambda { [200, {}, "Success!"] }
        #      match 'path', :to => RackApp
330 331 332
        #
        # [:on]
        #   Shorthand for wrapping routes in a specific RESTful context. Valid
333
        #   values are +:member+, +:collection+, and +:new+. Only use within
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        #   <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
350
        #   object that responds to <tt>matches?</tt>
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        #
        #     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.
369 370
        #
        # [:anchor]
371
        #   Boolean to anchor a <tt>match</tt> pattern. Default is true. When set to
372 373 374 375
        #   false, the pattern matches any request prefixed with the given path.
        #
        #     # Matches any request starting with 'path'
        #     match 'path' => 'c#a', :anchor => false
376
        def match(path, options=nil)
377 378 379
          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)
380 381
          self
        end
382

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

413 414
          options[:as] ||= app_name(app)

415
          match(path, options.merge(:to => app, :anchor => false, :format => false))
416 417

          define_generate_prefix(app, options[:as])
418 419 420
          self
        end

421 422 423 424
        def default_url_options=(options)
          @set.default_url_options = options
        end
        alias_method :default_url_options, :default_url_options=
425

426 427 428 429 430 431
        def with_default_scope(scope, &block)
          scope(scope) do
            instance_exec(&block)
          end
        end

432 433 434
        private
          def app_name(app)
            return unless app.respond_to?(:routes)
435 436 437 438 439 440 441

            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
442 443 444
          end

          def define_generate_prefix(app, name)
445
            return unless app.respond_to?(:routes) && app.routes.respond_to?(:define_mounted_helper)
446 447

            _route = @set.named_routes.routes[name.to_sym]
P
Piotr Sarnacki 已提交
448 449
            _routes = @set
            app.routes.define_mounted_helper(name)
450 451
            app.routes.class_eval do
              define_method :_generate_prefix do |options|
P
Piotr Sarnacki 已提交
452
                prefix_options = options.slice(*_route.segment_keys)
453 454
                # 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 已提交
455 456 457
                prefix = _routes.url_helpers.send("#{name}_path", prefix_options)
                prefix = '' if prefix == '/'
                prefix
458 459 460
              end
            end
          end
461 462 463
      end

      module HttpHelpers
464
        # Define a route that only recognizes HTTP GET.
465
        # For supported arguments, see <tt>Base#match</tt>.
466 467 468 469
        #
        # Example:
        #
        # get 'bacon', :to => 'food#bacon'
470 471 472 473
        def get(*args, &block)
          map_method(:get, *args, &block)
        end

474
        # Define a route that only recognizes HTTP POST.
475
        # For supported arguments, see <tt>Base#match</tt>.
476 477 478 479
        #
        # Example:
        #
        # post 'bacon', :to => 'food#bacon'
480 481 482 483
        def post(*args, &block)
          map_method(:post, *args, &block)
        end

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

494
        # Define a route that only recognizes HTTP PUT.
495
        # For supported arguments, see <tt>Base#match</tt>.
496 497 498 499
        #
        # Example:
        #
        # delete 'broccoli', :to => 'food#broccoli'
500 501 502 503 504 505 506 507 508 509 510 511 512 513
        def delete(*args, &block)
          map_method(:delete, *args, &block)
        end

        private
          def map_method(method, *args, &block)
            options = args.extract_options!
            options[:via] = method
            args.push(options)
            match(*args, &block)
            self
          end
      end

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

605
          options[:path] = args.first if args.first.is_a?(String)
606
          recover = {}
607

608 609 610
          options[:constraints] ||= {}
          unless options[:constraints].is_a?(Hash)
            block, options[:constraints] = options[:constraints], {}
611
          end
612

613 614 615 616 617
          scope_options.each do |option|
            if value = options.delete(option)
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
618 619
          end

620 621
          recover[:block] = @scope[:blocks]
          @scope[:blocks] = merge_blocks_scope(@scope[:blocks], block)
622

623 624
          recover[:options] = @scope[:options]
          @scope[:options]  = merge_options_scope(@scope[:options], options)
625 626 627 628

          yield
          self
        ensure
629 630 631 632 633 634
          scope_options.each do |option|
            @scope[option] = recover[option] if recover.has_key?(option)
          end

          @scope[:options] = recover[:options]
          @scope[:blocks]  = recover[:block]
635 636
        end

637 638 639 640 641 642
        # Scopes routes to a specific controller
        #
        # Example:
        #   controller "food" do
        #     match "bacon", :action => "bacon"
        #   end
643 644 645
        def controller(controller, options={})
          options[:controller] = controller
          scope(options) { yield }
646 647
        end

648 649 650 651 652 653 654 655
        # Scopes routes to a specific namespace. For example:
        #
        #   namespace :admin do
        #     resources :posts
        #   end
        #
        # This generates the following routes:
        #
656 657 658 659 660 661 662
        #       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
        #        admin_post PUT    /admin/posts/:id(.:format)      admin/posts#update
        #        admin_post DELETE /admin/posts/:id(.:format)      admin/posts#destroy
663
        #
664
        # === Options
665
        #
666 667
        # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
        # options all default to the name of the namespace.
668
        #
669 670
        # For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
        # <tt>Resources#resources</tt>.
671
        #
672
        # === Examples
673
        #
674 675 676 677
        #   # accessible through /sekret/posts rather than /admin/posts
        #   namespace :admin, :path => "sekret" do
        #     resources :posts
        #   end
678
        #
S
Sebastian Martinez 已提交
679
        #   # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
680 681 682
        #   namespace :admin, :module => "sekret" do
        #     resources :posts
        #   end
683
        #
S
Sebastian Martinez 已提交
684
        #   # generates +sekret_posts_path+ rather than +admin_posts_path+
685 686 687
        #   namespace :admin, :as => "sekret" do
        #     resources :posts
        #   end
688
        def namespace(path, options = {})
689
          path = path.to_s
690 691 692
          options = { :path => path, :as => path, :module => path,
                      :shallow_path => path, :shallow_prefix => path }.merge!(options)
          scope(options) { yield }
693
        end
694

R
Ryan Bigg 已提交
695 696 697 698 699 700 701 702 703 704
        # === 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:
        #
        #   constraints(:id => /\d+\.\d+) do
        #     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.
705
        #
R
R.T. Lechow 已提交
706
        # You may use this to also restrict other parameters:
R
Ryan Bigg 已提交
707 708 709 710 711
        #
        #   resources :posts do
        #     constraints(:post_id => /\d+\.\d+) do
        #       resources :comments
        #     end
J
James Miller 已提交
712
        #   end
R
Ryan Bigg 已提交
713 714 715 716 717 718 719 720 721 722 723 724 725 726
        #
        # === 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 已提交
727
        # Requests to routes can be constrained based on specific criteria:
R
Ryan Bigg 已提交
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        #
        #    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
        #      def self.matches(request)
        #        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
750 751 752 753
        def constraints(constraints = {})
          scope(:constraints => constraints) { yield }
        end

R
Ryan Bigg 已提交
754
        # Allows you to set default parameters for a route, such as this:
755 756 757
        #   defaults :id => 'home' do
        #     match 'scoped_pages/(:id)', :to => 'pages#show'
        #   end
R
Ryan Bigg 已提交
758
        # Using this, the +:id+ parameter here will default to 'home'.
759 760 761 762
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

763
        private
J
José Valim 已提交
764
          def scope_options #:nodoc:
765 766 767
            @scope_options ||= private_methods.grep(/^merge_(.+)_scope$/) { $1.to_sym }
          end

J
José Valim 已提交
768
          def merge_path_scope(parent, child) #:nodoc:
769
            Mapper.normalize_path("#{parent}/#{child}")
770 771
          end

J
José Valim 已提交
772
          def merge_shallow_path_scope(parent, child) #:nodoc:
773 774 775
            Mapper.normalize_path("#{parent}/#{child}")
          end

J
José Valim 已提交
776
          def merge_as_scope(parent, child) #:nodoc:
777
            parent ? "#{parent}_#{child}" : child
778 779
          end

J
José Valim 已提交
780
          def merge_shallow_prefix_scope(parent, child) #:nodoc:
781 782 783
            parent ? "#{parent}_#{child}" : child
          end

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

J
José Valim 已提交
788
          def merge_controller_scope(parent, child) #:nodoc:
789
            child
790 791
          end

J
José Valim 已提交
792
          def merge_path_names_scope(parent, child) #:nodoc:
793 794 795
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
796
          def merge_constraints_scope(parent, child) #:nodoc:
797 798 799
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
800
          def merge_defaults_scope(parent, child) #:nodoc:
801 802 803
            merge_options_scope(parent, child)
          end

J
José Valim 已提交
804
          def merge_blocks_scope(parent, child) #:nodoc:
805 806 807
            merged = parent ? parent.dup : []
            merged << child if child
            merged
808 809
          end

J
José Valim 已提交
810
          def merge_options_scope(parent, child) #:nodoc:
811
            (parent || {}).except(*override_keys(child)).merge(child)
812
          end
813

J
José Valim 已提交
814
          def merge_shallow_scope(parent, child) #:nodoc:
815 816
            child ? true : false
          end
817

J
José Valim 已提交
818
          def override_keys(child) #:nodoc:
819 820
            child.key?(:only) || child.key?(:except) ? [:only, :except] : []
          end
821 822
      end

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

869
        class Resource #:nodoc:
870
          DEFAULT_ACTIONS = [:index, :create, :new, :show, :update, :destroy, :edit]
871

872
          attr_reader :controller, :path, :options
873 874

          def initialize(entities, options = {})
875
            @name       = entities.to_s
876 877 878
            @path       = (options[:path] || @name).to_s
            @controller = (options[:controller] || @name).to_s
            @as         = options[:as]
879
            @options    = options
880 881
          end

882
          def default_actions
883
            self.class::DEFAULT_ACTIONS
884 885
          end

886
          def actions
887
            if only = @options[:only]
888
              Array(only).map(&:to_sym)
889
            elsif except = @options[:except]
890 891 892 893 894 895
              default_actions - Array(except).map(&:to_sym)
            else
              default_actions
            end
          end

896
          def name
897
            @as || @name
898 899
          end

900
          def plural
901
            @plural ||= name.to_s
902 903 904
          end

          def singular
905
            @singular ||= name.to_s.singularize
906 907
          end

908
          alias :member_name :singular
909

910
          # Checks for uncountable plurals, and appends "_index" if the plural
911
          # and singular form are the same.
912
          def collection_name
913
            singular == plural ? "#{plural}_index" : plural
914 915
          end

916
          def resource_scope
917
            { :controller => controller }
918 919
          end

920
          alias :collection_scope :path
921 922

          def member_scope
923
            "#{path}/:id"
924 925
          end

926
          def new_scope(new_path)
927
            "#{path}/#{new_path}"
928 929 930
          end

          def nested_scope
931
            "#{path}/:#{singular}_id"
932
          end
933

934 935 936
        end

        class SingletonResource < Resource #:nodoc:
937
          DEFAULT_ACTIONS = [:show, :create, :update, :destroy, :new, :edit]
938

939
          def initialize(entities, options)
940 941
            super

942
            @as         = nil
943 944
            @controller = (options[:controller] || plural).to_s
            @as         = options[:as]
945 946
          end

947 948
          def plural
            @plural ||= name.to_s.pluralize
949 950
          end

951 952
          def singular
            @singular ||= name.to_s
953
          end
954 955 956 957 958 959

          alias :member_name :singular
          alias :collection_name :singular

          alias :member_scope :path
          alias :nested_scope :path
960 961
        end

962 963 964 965
        def resources_path_names(options)
          @scope[:path_names].merge!(options)
        end

966 967 968 969 970 971 972 973 974
        # 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 已提交
975
        # the +GeoCoders+ controller (note that the controller is named after
976 977 978 979 980 981 982 983
        # the plural):
        #
        #   GET     /geocoder/new
        #   POST    /geocoder
        #   GET     /geocoder
        #   GET     /geocoder/edit
        #   PUT     /geocoder
        #   DELETE  /geocoder
984
        #
985
        # === Options
986
        # Takes same options as +resources+.
J
Joshua Peek 已提交
987
        def resource(*resources, &block)
J
Joshua Peek 已提交
988
          options = resources.extract_options!
J
Joshua Peek 已提交
989

990
          if apply_common_behavior_for(:resource, resources, options, &block)
991 992 993
            return self
          end

994 995
          resource_scope(SingletonResource.new(resources.pop, options)) do
            yield if block_given?
996

997
            collection do
998
              post :create
999
            end if parent_resource.actions.include?(:create)
1000

1001
            new do
1002
              get :new
1003
            end if parent_resource.actions.include?(:new)
1004

1005
            member do
1006
              get    :edit if parent_resource.actions.include?(:edit)
1007 1008 1009
              get    :show if parent_resource.actions.include?(:show)
              put    :update if parent_resource.actions.include?(:update)
              delete :destroy if parent_resource.actions.include?(:destroy)
1010 1011 1012
            end
          end

J
Joshua Peek 已提交
1013
          self
1014 1015
        end

1016 1017 1018 1019 1020 1021 1022 1023
        # 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 已提交
1024
        # the +Photos+ controller:
1025 1026 1027 1028 1029 1030 1031
        #
        #   GET     /photos/new
        #   POST    /photos
        #   GET     /photos/:id
        #   GET     /photos/:id/edit
        #   PUT     /photos/:id
        #   DELETE  /photos/:id
1032
        #
1033 1034 1035 1036 1037 1038 1039 1040
        # Resources can also be nested infinitely by using this block syntax:
        #
        #   resources :photos do
        #     resources :comments
        #   end
        #
        # This generates the following comments routes:
        #
1041 1042 1043 1044 1045 1046
        #   GET     /photos/:photo_id/comments/new
        #   POST    /photos/:photo_id/comments
        #   GET     /photos/:photo_id/comments/:id
        #   GET     /photos/:photo_id/comments/:id/edit
        #   PUT     /photos/:photo_id/comments/:id
        #   DELETE  /photos/:photo_id/comments/:id
1047
        #
1048
        # === Options
1049 1050
        # Takes same options as <tt>Base#match</tt> as well as:
        #
1051 1052 1053 1054 1055 1056 1057
        # [:path_names]
        #   Allows you to change the paths of the seven default actions.
        #   Paths not specified are not changed.
        #
        #     resources :posts, :path_names => { :new => "brand_new" }
        #
        #   The above example will now change /posts/new to /posts/brand_new
1058
        #
1059 1060
        # [:only]
        #   Only generate routes for the given actions.
1061
        #
1062 1063
        #     resources :cows, :only => :show
        #     resources :cows, :only => [:show, :index]
1064
        #
1065 1066
        # [:except]
        #   Generate all routes except for the given actions.
1067
        #
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
        #     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
1082
        #       resources :comments, :except => [:show, :edit, :update, :destroy]
1083
        #     end
1084 1085 1086 1087 1088
        #     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>.
1089 1090 1091 1092
        #
        # [:shallow_path]
        #   Prefixes nested shallow routes with the specified path.
        #
1093 1094 1095 1096
        #     scope :shallow_path => "sekret" do
        #       resources :posts do
        #         resources :comments, :shallow => true
        #       end
1097 1098 1099 1100
        #     end
        #
        #   The +comments+ resource here will have the following routes generated for it:
        #
G
ganesh 已提交
1101 1102 1103
        #     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)
1104 1105 1106 1107 1108 1109
        #     edit_comment     GET    /sekret/comments/:id/edit(.:format)
        #     comment          GET    /sekret/comments/:id(.:format)
        #     comment          PUT    /sekret/comments/:id(.:format)
        #     comment          DELETE /sekret/comments/:id(.:format)
        #
        # === Examples
1110
        #
S
Sebastian Martinez 已提交
1111
        #   # routes call <tt>Admin::PostsController</tt>
1112
        #   resources :posts, :module => "admin"
1113
        #
1114
        #   # resource actions are at /admin/posts.
1115
        #   resources :posts, :path => "admin/posts"
J
Joshua Peek 已提交
1116
        def resources(*resources, &block)
J
Joshua Peek 已提交
1117
          options = resources.extract_options!
1118

1119
          if apply_common_behavior_for(:resources, resources, options, &block)
1120 1121 1122
            return self
          end

1123
          resource_scope(Resource.new(resources.pop, options)) do
1124
            yield if block_given?
J
Joshua Peek 已提交
1125

1126
            collection do
1127 1128
              get  :index if parent_resource.actions.include?(:index)
              post :create if parent_resource.actions.include?(:create)
1129
            end
1130

1131
            new do
1132
              get :new
1133
            end if parent_resource.actions.include?(:new)
1134

1135
            member do
1136
              get    :edit if parent_resource.actions.include?(:edit)
1137 1138 1139
              get    :show if parent_resource.actions.include?(:show)
              put    :update if parent_resource.actions.include?(:update)
              delete :destroy if parent_resource.actions.include?(:destroy)
1140 1141 1142
            end
          end

J
Joshua Peek 已提交
1143
          self
1144 1145
        end

1146 1147 1148 1149 1150 1151 1152 1153 1154
        # 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 已提交
1155
        # with GET, and route to the search action of +PhotosController+. It will also
1156 1157
        # create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
        # route helpers.
J
Joshua Peek 已提交
1158
        def collection
1159 1160
          unless resource_scope?
            raise ArgumentError, "can't use collection outside resource(s) scope"
1161 1162
          end

1163 1164 1165 1166
          with_scope_level(:collection) do
            scope(parent_resource.collection_scope) do
              yield
            end
J
Joshua Peek 已提交
1167
          end
1168
        end
J
Joshua Peek 已提交
1169

1170 1171 1172 1173 1174 1175 1176 1177 1178
        # 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 已提交
1179
        # preview action of +PhotosController+. It will also create the
1180
        # <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
J
Joshua Peek 已提交
1181
        def member
1182 1183
          unless resource_scope?
            raise ArgumentError, "can't use member outside resource(s) scope"
J
Joshua Peek 已提交
1184
          end
J
Joshua Peek 已提交
1185

1186 1187 1188 1189
          with_scope_level(:member) do
            scope(parent_resource.member_scope) do
              yield
            end
1190 1191 1192 1193 1194 1195 1196
          end
        end

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

1198 1199 1200 1201
          with_scope_level(:new) do
            scope(parent_resource.new_scope(action_path(:new))) do
              yield
            end
J
Joshua Peek 已提交
1202
          end
J
Joshua Peek 已提交
1203 1204
        end

1205
        def nested
1206 1207
          unless resource_scope?
            raise ArgumentError, "can't use nested outside resource(s) scope"
1208 1209 1210
          end

          with_scope_level(:nested) do
1211
            if shallow?
1212
              with_exclusive_scope do
1213
                if @scope[:shallow_path].blank?
1214
                  scope(parent_resource.nested_scope, nested_options) { yield }
1215
                else
1216
                  scope(@scope[:shallow_path], :as => @scope[:shallow_prefix]) do
1217
                    scope(parent_resource.nested_scope, nested_options) { yield }
1218 1219 1220 1221
                  end
                end
              end
            else
1222
              scope(parent_resource.nested_scope, nested_options) { yield }
1223 1224 1225 1226
            end
          end
        end

1227
        # See ActionDispatch::Routing::Mapper::Scoping#namespace
1228
        def namespace(path, options = {})
1229
          if resource_scope?
1230 1231 1232 1233 1234 1235
            nested { super }
          else
            super
          end
        end

1236
        def shallow
1237
          scope(:shallow => true, :shallow_path => @scope[:path]) do
1238 1239 1240 1241
            yield
          end
        end

1242 1243 1244 1245
        def shallow?
          parent_resource.instance_of?(Resource) && @scope[:shallow]
        end

J
Joshua Peek 已提交
1246
        def match(*args)
1247
          options = args.extract_options!.dup
1248 1249
          options[:anchor] = true unless options.key?(:anchor)

1250
          if args.length > 1
1251
            args.each { |path| match(path, options.dup) }
1252 1253 1254
            return self
          end

1255 1256
          on = options.delete(:on)
          if VALID_ON_OPTIONS.include?(on)
1257
            args.push(options)
1258 1259 1260
            return send(on){ match(*args) }
          elsif on
            raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
1261 1262
          end

1263 1264 1265 1266
          if @scope[:scope_level] == :resources
            args.push(options)
            return nested { match(*args) }
          elsif @scope[:scope_level] == :resource
1267
            args.push(options)
J
Joshua Peek 已提交
1268 1269
            return member { match(*args) }
          end
J
Joshua Peek 已提交
1270

1271
          action = args.first
1272
          path = path_for_action(action, options.delete(:path))
1273

1274 1275 1276
          if action.to_s =~ /^[\w\/]+$/
            options[:action] ||= action unless action.to_s.include?("/")
          else
1277 1278 1279 1280 1281 1282 1283
            action = nil
          end

          if options.key?(:as) && !options[:as]
            options.delete(:as)
          else
            options[:as] = name_for_action(options[:as], action)
J
Joshua Peek 已提交
1284
          end
J
Joshua Peek 已提交
1285

1286
          super(path, options)
J
Joshua Peek 已提交
1287 1288
        end

1289
        def root(options={})
1290
          if @scope[:scope_level] == :resources
1291 1292
            with_scope_level(:root) do
              scope(parent_resource.path) do
1293 1294 1295 1296 1297 1298
                super(options)
              end
            end
          else
            super(options)
          end
1299 1300
        end

1301
        protected
1302

1303
          def parent_resource #:nodoc:
1304 1305 1306
            @scope[:scope_level_resource]
          end

J
José Valim 已提交
1307
          def apply_common_behavior_for(method, resources, options, &block) #:nodoc:
1308 1309 1310 1311 1312
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

1313 1314 1315 1316 1317
            if resource_scope?
              nested { send(method, resources.pop, options, &block) }
              return true
            end

1318
            options.keys.each do |k|
1319 1320 1321
              (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
            end

1322 1323 1324
            scope_options = options.slice!(*RESOURCE_OPTIONS)
            unless scope_options.empty?
              scope(scope_options) do
1325 1326 1327 1328 1329
                send(method, resources.pop, options, &block)
              end
              return true
            end

1330 1331 1332 1333
            unless action_options?(options)
              options.merge!(scope_action_options) if scope_action_options?
            end

1334 1335 1336
            false
          end

J
José Valim 已提交
1337
          def action_options?(options) #:nodoc:
1338 1339 1340
            options[:only] || options[:except]
          end

J
José Valim 已提交
1341
          def scope_action_options? #:nodoc:
1342 1343 1344
            @scope[:options].is_a?(Hash) && (@scope[:options][:only] || @scope[:options][:except])
          end

J
José Valim 已提交
1345
          def scope_action_options #:nodoc:
1346 1347 1348
            @scope[:options].slice(:only, :except)
          end

J
José Valim 已提交
1349
          def resource_scope? #:nodoc:
1350
            @scope[:scope_level].in?([:resource, :resources])
1351 1352
          end

J
José Valim 已提交
1353
          def resource_method_scope? #:nodoc:
1354
            @scope[:scope_level].in?([:collection, :member, :new])
1355 1356
          end

1357
          def with_exclusive_scope
1358
            begin
1359 1360
              old_name_prefix, old_path = @scope[:as], @scope[:path]
              @scope[:as], @scope[:path] = nil, nil
1361

1362 1363 1364
              with_scope_level(:exclusive) do
                yield
              end
1365
            ensure
1366
              @scope[:as], @scope[:path] = old_name_prefix, old_path
1367 1368 1369
            end
          end

1370
          def with_scope_level(kind, resource = parent_resource)
J
Joshua Peek 已提交
1371
            old, @scope[:scope_level] = @scope[:scope_level], kind
1372
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
J
Joshua Peek 已提交
1373 1374 1375
            yield
          ensure
            @scope[:scope_level] = old
1376
            @scope[:scope_level_resource] = old_resource
J
Joshua Peek 已提交
1377
          end
1378

J
José Valim 已提交
1379
          def resource_scope(resource) #:nodoc:
1380
            with_scope_level(resource.is_a?(SingletonResource) ? :resource : :resources, resource) do
1381
              scope(parent_resource.resource_scope) do
1382 1383 1384 1385 1386
                yield
              end
            end
          end

J
José Valim 已提交
1387
          def nested_options #:nodoc:
1388 1389 1390 1391 1392 1393
            {}.tap do |options|
              options[:as] = parent_resource.member_name
              options[:constraints] = { "#{parent_resource.singular}_id".to_sym => id_constraint } if id_constraint?
            end
          end

J
José Valim 已提交
1394
          def id_constraint? #:nodoc:
1395
            @scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp)
1396 1397
          end

J
José Valim 已提交
1398
          def id_constraint #:nodoc:
1399
            @scope[:constraints][:id]
1400 1401
          end

J
José Valim 已提交
1402
          def canonical_action?(action, flag) #:nodoc:
1403
            flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
1404 1405
          end

J
José Valim 已提交
1406
          def shallow_scoping? #:nodoc:
1407
            shallow? && @scope[:scope_level] == :member
1408 1409
          end

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

1414 1415
            path = if canonical_action?(action, path.blank?)
              prefix.to_s
1416
            else
1417
              "#{prefix}/#{action_path(action, path)}"
1418 1419 1420
            end
          end

J
José Valim 已提交
1421
          def action_path(name, path = nil) #:nodoc:
1422 1423 1424
            # Ruby 1.8 can't transform empty strings to symbols
            name = name.to_sym if name.is_a?(String) && !name.empty?
            path || @scope[:path_names][name] || name.to_s
1425 1426
          end

J
José Valim 已提交
1427
          def prefix_name_for_action(as, action) #:nodoc:
1428
            if as
1429
              as.to_s
1430
            elsif !canonical_action?(action, @scope[:scope_level])
1431
              action.to_s
1432
            end
1433 1434
          end

J
José Valim 已提交
1435
          def name_for_action(as, action) #:nodoc:
1436
            prefix = prefix_name_for_action(as, action)
1437
            prefix = Mapper.normalize_name(prefix) if prefix
1438 1439 1440
            name_prefix = @scope[:as]

            if parent_resource
1441
              return nil unless as || action
1442

1443 1444
              collection_name = parent_resource.collection_name
              member_name = parent_resource.member_name
1445
            end
1446

1447
            name = case @scope[:scope_level]
1448
            when :nested
1449
              [name_prefix, prefix]
1450
            when :collection
1451
              [prefix, name_prefix, collection_name]
1452
            when :new
1453 1454 1455 1456 1457
              [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]
1458
            else
1459
              [name_prefix, member_name, prefix]
1460
            end
1461

1462
            candidate = name.select(&:present?).join("_").presence
1463
            candidate unless as.nil? && @set.routes.find { |r| r.name == candidate }
1464
          end
J
Joshua Peek 已提交
1465
      end
J
Joshua Peek 已提交
1466

J
José Valim 已提交
1467
      module Shorthand #:nodoc:
1468 1469 1470
        def match(path, *rest)
          if rest.empty? && Hash === path
            options  = path
1471 1472 1473 1474 1475 1476 1477 1478 1479
            path, to = options.find { |name, value| name.is_a?(String) }
            options.merge!(:to => to).delete(path)
            super(path, options)
          else
            super
          end
        end
      end

1480 1481 1482 1483 1484
      def initialize(set) #:nodoc:
        @set = set
        @scope = { :path_names => @set.resources_path_names }
      end

1485 1486
      include Base
      include HttpHelpers
1487
      include Redirection
1488 1489
      include Scoping
      include Resources
1490
      include Shorthand
J
Joshua Peek 已提交
1491 1492
    end
  end
J
Joshua Peek 已提交
1493
end