mapper.rb 50.0 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
        # A pattern can also point to a +Rack+ endpoint i.e. anything that
        # responds to +call+:
        #
A
Alexey Vakhov 已提交
288
        #   match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon"] }
289 290 291 292
        #   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
        # === 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 已提交
699
        #   constraints(:id => /\d+\.\d+/) do
R
Ryan Bigg 已提交
700 701 702 703 704
        #     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
        #
        #   resources :posts do
M
mjy 已提交
709
        #     constraints(:post_id => /\d+\.\d+/) do
R
Ryan Bigg 已提交
710 711
        #       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
        #
        #    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
738
        #      def self.matches?(request)
R
Ryan Bigg 已提交
739 740 741 742 743 744 745 746 747 748 749
        #        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
        #
A
Alexey Vakhov 已提交
1026
        #   GET     /photos
1027 1028 1029 1030 1031 1032
        #   GET     /photos/new
        #   POST    /photos
        #   GET     /photos/:id
        #   GET     /photos/:id/edit
        #   PUT     /photos/:id
        #   DELETE  /photos/:id
1033
        #
1034 1035 1036 1037 1038 1039 1040 1041
        # Resources can also be nested infinitely by using this block syntax:
        #
        #   resources :photos do
        #     resources :comments
        #   end
        #
        # This generates the following comments routes:
        #
A
Alexey Vakhov 已提交
1042
        #   GET     /photos/:photo_id/comments
1043 1044 1045 1046 1047 1048
        #   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
1049
        #
1050
        # === Options
1051 1052
        # Takes same options as <tt>Base#match</tt> as well as:
        #
1053 1054 1055 1056 1057 1058 1059
        # [: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
1060
        #
1061 1062
        # [:only]
        #   Only generate routes for the given actions.
1063
        #
1064 1065
        #     resources :cows, :only => :show
        #     resources :cows, :only => [:show, :index]
1066
        #
1067 1068
        # [:except]
        #   Generate all routes except for the given actions.
1069
        #
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
        #     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
1084
        #       resources :comments, :except => [:show, :edit, :update, :destroy]
1085
        #     end
1086 1087 1088 1089 1090
        #     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>.
1091 1092 1093 1094
        #
        # [:shallow_path]
        #   Prefixes nested shallow routes with the specified path.
        #
1095 1096 1097 1098
        #     scope :shallow_path => "sekret" do
        #       resources :posts do
        #         resources :comments, :shallow => true
        #       end
1099 1100 1101 1102
        #     end
        #
        #   The +comments+ resource here will have the following routes generated for it:
        #
G
ganesh 已提交
1103 1104 1105
        #     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)
1106 1107 1108 1109 1110 1111
        #     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
1112
        #
S
Sebastian Martinez 已提交
1113
        #   # routes call <tt>Admin::PostsController</tt>
1114
        #   resources :posts, :module => "admin"
1115
        #
1116
        #   # resource actions are at /admin/posts.
1117
        #   resources :posts, :path => "admin/posts"
J
Joshua Peek 已提交
1118
        def resources(*resources, &block)
J
Joshua Peek 已提交
1119
          options = resources.extract_options!
1120

1121
          if apply_common_behavior_for(:resources, resources, options, &block)
1122 1123 1124
            return self
          end

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

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

1133
            new do
1134
              get :new
1135
            end if parent_resource.actions.include?(:new)
1136

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

J
Joshua Peek 已提交
1145
          self
1146 1147
        end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1273
          action = args.first
1274
          path = path_for_action(action, options.delete(:path))
1275

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

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

1288
          super(path, options)
J
Joshua Peek 已提交
1289 1290
        end

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

1303
        protected
1304

1305
          def parent_resource #:nodoc:
1306 1307 1308
            @scope[:scope_level_resource]
          end

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

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

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

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

1332 1333 1334 1335
            unless action_options?(options)
              options.merge!(scope_action_options) if scope_action_options?
            end

1336 1337 1338
            false
          end

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

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

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

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

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

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

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

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

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

J
José Valim 已提交
1389
          def nested_options #:nodoc:
1390 1391 1392 1393 1394 1395
            {}.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 已提交
1396
          def id_constraint? #:nodoc:
1397
            @scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp)
1398 1399
          end

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

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

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

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

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

J
José Valim 已提交
1423
          def action_path(name, path = nil) #:nodoc:
1424 1425 1426
            # 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
1427 1428
          end

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

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

            if parent_resource
1443
              return nil unless as || action
1444

1445 1446
              collection_name = parent_resource.collection_name
              member_name = parent_resource.member_name
1447
            end
1448

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

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

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

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

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