mapper.rb 27.7 KB
Newer Older
1
require 'erb'
2
require 'active_support/core_ext/hash/except'
3
require 'active_support/core_ext/object/blank'
4

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

17 18
        attr_reader :app

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

        def call(env)
24
          req = @request.new(env)
25 26 27

          @constraints.each { |constraint|
            if constraint.respond_to?(:matches?) && !constraint.matches?(req)
J
Joshua Peek 已提交
28
              return [ 404, {'X-Cascade' => 'pass'}, [] ]
29
            elsif constraint.respond_to?(:call) && !constraint.call(*constraint_args(constraint, req))
J
Joshua Peek 已提交
30
              return [ 404, {'X-Cascade' => 'pass'}, [] ]
31 32 33 34 35
            end
          }

          @app.call(env)
        end
36 37 38 39 40

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

43
      class Mapping #:nodoc:
44
        IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix]
45

46
        def initialize(set, scope, path, options)
47 48
          @set, @scope = set, scope
          @options = (@scope[:options] || {}).merge(options)
49
          @path = normalize_path(path)
50
          normalize_options!
51
        end
J
Joshua Peek 已提交
52

53
        def to_route
54
          [ app, conditions, requirements, defaults, @options[:as], @options[:anchor] ]
55
        end
J
Joshua Peek 已提交
56

57
        private
58 59 60

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

62 63 64
            if using_match_shorthand?(path_without_format, @options)
              to_shorthand    = @options[:to].blank?
              @options[:to] ||= path_without_format[1..-1].sub(%r{/([^/]*)$}, '#\1')
65
              @options[:as] ||= Mapper.normalize_name(path_without_format)
66 67
            end

68
            @options.merge!(default_controller_and_action(to_shorthand))
69
          end
70

71
          # match "account/overview"
72
          def using_match_shorthand?(path, options)
73
            path && options.except(:via, :anchor, :to, :as).empty? && path =~ %r{^/[\w\/]+$}
74
          end
75

76
          def normalize_path(path)
77 78
            raise ArgumentError, "path is required" if path.blank?
            path = Mapper.normalize_path(path)
79 80 81 82 83 84 85 86 87 88 89

            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' }
              @options.reverse_merge!(:controller => /.+?/)
            end

90 91 92 93
            if @options[:format] == false
              @options.delete(:format)
              path
            elsif path.include?(":format")
94 95 96 97
              path
            else
              "#{path}(.:format)"
            end
98
          end
99

100 101
          def app
            Constraints.new(
102
              to.respond_to?(:call) ? to : Routing::RouteSet::Dispatcher.new(:defaults => defaults),
103 104
              blocks,
              @set.request_class
105
            )
106 107
          end

108 109 110
          def conditions
            { :path_info => @path }.merge(constraints).merge(request_method_condition)
          end
J
Joshua Peek 已提交
111

112
          def requirements
113
            @requirements ||= (@options[:constraints].is_a?(Hash) ? @options[:constraints] : {}).tap do |requirements|
114 115 116 117
              requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints]
              @options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) }
            end
          end
118

119
          def defaults
120 121 122 123 124 125
            @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

126
          def default_controller_and_action(to_shorthand=nil)
127
            if to.respond_to?(:call)
128 129
              { }
            else
130
              if to.is_a?(String)
131
                controller, action = to.split('#')
132 133
              elsif to.is_a?(Symbol)
                action = to.to_s
134
              end
J
Joshua Peek 已提交
135

136 137
              controller ||= default_controller
              action     ||= default_action
138

139 140 141
              unless controller.is_a?(Regexp) || to_shorthand
                controller = [@scope[:module], controller].compact.join("/").presence
              end
142

143 144
              controller = controller.to_s unless controller.is_a?(Regexp)
              action     = action.to_s     unless action.is_a?(Regexp)
145

146
              if controller.blank? && segment_keys.exclude?("controller")
147 148
                raise ArgumentError, "missing :controller"
              end
J
Joshua Peek 已提交
149

150
              if action.blank? && segment_keys.exclude?("action")
151 152
                raise ArgumentError, "missing :action"
              end
J
Joshua Peek 已提交
153

154 155 156 157
              { :controller => controller, :action => action }.tap do |hash|
                hash.delete(:controller) if hash[:controller].blank?
                hash.delete(:action)     if hash[:action].blank?
              end
158 159
            end
          end
160

161 162 163 164 165 166
          def blocks
            if @options[:constraints].present? && !@options[:constraints].is_a?(Hash)
              block = @options[:constraints]
            else
              block = nil
            end
J
Joshua Peek 已提交
167 168

            ((@scope[:blocks] || []) + [ block ]).compact
169
          end
J
Joshua Peek 已提交
170

171 172 173
          def constraints
            @constraints ||= requirements.reject { |k, v| segment_keys.include?(k.to_s) || k == :controller }
          end
174

175 176 177 178 179 180
          def request_method_condition
            if via = @options[:via]
              via = Array(via).map { |m| m.to_s.upcase }
              { :request_method => Regexp.union(*via) }
            else
              { }
181
            end
182
          end
J
Joshua Peek 已提交
183

184 185
          def segment_keys
            @segment_keys ||= Rack::Mount::RegexpWithNamedGroups.new(
186 187
              Rack::Mount::Strexp.compile(@path, requirements, SEPARATORS)
            ).names
188
          end
189

190 191 192
          def to
            @options[:to]
          end
J
Joshua Peek 已提交
193

194
          def default_controller
195
            if @options[:controller]
196
              @options[:controller]
197
            elsif @scope[:controller]
198
              @scope[:controller]
199
            end
200
          end
201 202 203

          def default_action
            if @options[:action]
204
              @options[:action]
205 206
            elsif @scope[:action]
              @scope[:action]
207 208
            end
          end
209
      end
210

211
      # Invokes Rack::Mount::Utils.normalize path and ensure that
212 213
      # (:locale) becomes (/:locale) instead of /(:locale). Except
      # for root cases, where the latter is the correct one.
214 215
      def self.normalize_path(path)
        path = Rack::Mount::Utils.normalize_path(path)
216
        path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^/]+\)$}
217 218 219
        path
      end

220 221 222 223
      def self.normalize_name(name)
        normalize_path(name)[1..-1].gsub("/", "_")
      end

224
      module Base
225
        def initialize(set) #:nodoc:
226 227
          @set = set
        end
228

229 230 231
        def root(options = {})
          match '/', options.reverse_merge(:as => :root)
        end
232

233 234
        def match(path, options=nil)
          mapping = Mapping.new(@set, @scope, path, options || {}).to_route
235
          @set.add_route(*mapping)
236 237
          self
        end
238

239 240 241 242 243 244 245 246 247 248 249
        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

250
          match(path, options.merge(:to => app, :anchor => false, :format => false))
251 252 253
          self
        end

254 255 256 257
        def default_url_options=(options)
          @set.default_url_options = options
        end
        alias_method :default_url_options, :default_url_options=
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
      end

      module HttpHelpers
        def get(*args, &block)
          map_method(:get, *args, &block)
        end

        def post(*args, &block)
          map_method(:post, *args, &block)
        end

        def put(*args, &block)
          map_method(:put, *args, &block)
        end

        def delete(*args, &block)
          map_method(:delete, *args, &block)
        end

277 278 279
        def redirect(*args, &block)
          options = args.last.is_a?(Hash) ? args.pop : {}

280 281 282
          path      = args.shift || block
          path_proc = path.is_a?(Proc) ? path : proc { |params| path % params }
          status    = options[:status] || 301
283 284

          lambda do |env|
285
            req = Request.new(env)
286 287 288 289 290

            params = [req.symbolized_path_parameters]
            params << req if path_proc.arity > 1

            uri = URI.parse(path_proc.call(*params))
291 292
            uri.scheme ||= req.scheme
            uri.host   ||= req.host
293
            uri.port   ||= req.port unless req.standard_port?
294

295 296
            body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)

297 298 299 300 301
            headers = {
              'Location' => uri.to_s,
              'Content-Type' => 'text/html',
              'Content-Length' => body.length.to_s
            }
302

303
            [ status, headers, [body] ]
304
          end
305 306 307 308 309 310 311 312 313 314 315 316 317
        end

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

      module Scoping
318
        def initialize(*args) #:nodoc:
319 320 321 322 323 324
          @scope = {}
          super
        end

        def scope(*args)
          options = args.extract_options!
325
          options = options.dup
326

327 328
          if name_prefix = options.delete(:name_prefix)
            options[:as] ||= name_prefix
329
            ActiveSupport::Deprecation.warn ":name_prefix was deprecated in the new router syntax. Use :as instead.", caller
330 331
          end

332
          options[:path] = args.first if args.first.is_a?(String)
333
          recover = {}
334

335 336 337
          options[:constraints] ||= {}
          unless options[:constraints].is_a?(Hash)
            block, options[:constraints] = options[:constraints], {}
338
          end
339

340 341 342 343 344
          scope_options.each do |option|
            if value = options.delete(option)
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
345 346
          end

347 348
          recover[:block] = @scope[:blocks]
          @scope[:blocks] = merge_blocks_scope(@scope[:blocks], block)
349

350 351
          recover[:options] = @scope[:options]
          @scope[:options]  = merge_options_scope(@scope[:options], options)
352 353 354 355

          yield
          self
        ensure
356 357 358 359 360 361
          scope_options.each do |option|
            @scope[option] = recover[option] if recover.has_key?(option)
          end

          @scope[:options] = recover[:options]
          @scope[:blocks]  = recover[:block]
362 363
        end

364 365 366
        def controller(controller, options={})
          options[:controller] = controller
          scope(options) { yield }
367 368
        end

369
        def namespace(path, options = {})
370
          path = path.to_s
371 372 373
          options = { :path => path, :as => path, :module => path,
                      :shallow_path => path, :shallow_prefix => path }.merge!(options)
          scope(options) { yield }
374 375 376 377 378 379
        end

        def constraints(constraints = {})
          scope(:constraints => constraints) { yield }
        end

380 381 382 383
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

384 385 386 387 388 389
        private
          def scope_options
            @scope_options ||= private_methods.grep(/^merge_(.+)_scope$/) { $1.to_sym }
          end

          def merge_path_scope(parent, child)
390
            Mapper.normalize_path("#{parent}/#{child}")
391 392
          end

393 394 395 396
          def merge_shallow_path_scope(parent, child)
            Mapper.normalize_path("#{parent}/#{child}")
          end

397
          def merge_as_scope(parent, child)
398
            parent ? "#{parent}_#{child}" : child
399 400
          end

401 402 403 404
          def merge_shallow_prefix_scope(parent, child)
            parent ? "#{parent}_#{child}" : child
          end

405
          def merge_module_scope(parent, child)
406 407 408 409
            parent ? "#{parent}/#{child}" : child
          end

          def merge_controller_scope(parent, child)
410
            child
411 412
          end

413
          def merge_path_names_scope(parent, child)
414 415 416 417 418 419 420
            merge_options_scope(parent, child)
          end

          def merge_constraints_scope(parent, child)
            merge_options_scope(parent, child)
          end

421 422 423 424
          def merge_defaults_scope(parent, child)
            merge_options_scope(parent, child)
          end

425
          def merge_blocks_scope(parent, child)
426 427 428
            merged = parent ? parent.dup : []
            merged << child if child
            merged
429 430 431
          end

          def merge_options_scope(parent, child)
432
            (parent || {}).except(*override_keys(child)).merge(child)
433
          end
434 435 436 437

          def merge_shallow_scope(parent, child)
            child ? true : false
          end
438 439 440 441

          def override_keys(child)
            child.key?(:only) || child.key?(:except) ? [:only, :except] : []
          end
442 443
      end

J
Joshua Peek 已提交
444
      module Resources
445 446
        # CANONICAL_ACTIONS holds all actions that does not need a prefix or
        # a path appended since they fit properly in their scope level.
447 448 449
        VALID_ON_OPTIONS  = [:new, :collection, :member]
        RESOURCE_OPTIONS  = [:as, :controller, :path, :only, :except]
        CANONICAL_ACTIONS = %w(index create new show update destroy)
450

451
        class Resource #:nodoc:
452
          DEFAULT_ACTIONS = [:index, :create, :new, :show, :update, :destroy, :edit]
453

454
          attr_reader :controller, :path, :options
455 456

          def initialize(entities, options = {})
457
            @name       = entities.to_s
458
            @path       = (options.delete(:path) || @name).to_s
459
            @controller = (options.delete(:controller) || @name).to_s
460
            @as         = options.delete(:as)
461
            @options    = options
462 463
          end

464
          def default_actions
465
            self.class::DEFAULT_ACTIONS
466 467
          end

468 469 470 471 472 473 474 475 476 477
          def actions
            if only = @options[:only]
              Array(only).map(&:to_sym)
            elsif except = @options[:except]
              default_actions - Array(except).map(&:to_sym)
            else
              default_actions
            end
          end

478
          def name
479
            @as || @name
480 481
          end

482
          def plural
483
            @plural ||= name.to_s
484 485 486
          end

          def singular
487
            @singular ||= name.to_s.singularize
488 489
          end

490
          alias :member_name :singular
491

492
          # Checks for uncountable plurals, and appends "_index" if they're.
493
          def collection_name
494
            singular == plural ? "#{plural}_index" : plural
495 496
          end

497
          def resource_scope
498
            { :controller => controller }
499 500
          end

501
          alias :collection_scope :path
502 503

          def member_scope
504
            "#{path}/:id"
505 506
          end

507
          def new_scope(new_path)
508
            "#{path}/#{new_path}"
509 510 511
          end

          def nested_scope
512
            "#{path}/:#{singular}_id"
513
          end
514

515 516 517
        end

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

520 521
          def initialize(entities, options)
            @name       = entities.to_s
522
            @path       = (options.delete(:path) || @name).to_s
523
            @controller = (options.delete(:controller) || plural).to_s
524 525 526 527
            @as         = options.delete(:as)
            @options    = options
          end

528 529
          def plural
            @plural ||= name.to_s.pluralize
530 531
          end

532 533
          def singular
            @singular ||= name.to_s
534
          end
535 536 537 538 539 540

          alias :member_name :singular
          alias :collection_name :singular

          alias :member_scope :path
          alias :nested_scope :path
541 542
        end

543
        def initialize(*args) #:nodoc:
544
          super
545
          @scope[:path_names] = @set.resources_path_names
546 547
        end

548 549 550 551
        def resources_path_names(options)
          @scope[:path_names].merge!(options)
        end

J
Joshua Peek 已提交
552
        def resource(*resources, &block)
J
Joshua Peek 已提交
553
          options = resources.extract_options!
J
Joshua Peek 已提交
554

555
          if apply_common_behavior_for(:resource, resources, options, &block)
556 557 558
            return self
          end

559 560
          resource_scope(SingletonResource.new(resources.pop, options)) do
            yield if block_given?
561

562
            collection_scope do
563
              post :create
564
            end if parent_resource.actions.include?(:create)
565 566 567

            new_scope do
              get :new
568
            end if parent_resource.actions.include?(:new)
569

570
            member_scope  do
571
              get    :edit if parent_resource.actions.include?(:edit)
572 573 574
              get    :show if parent_resource.actions.include?(:show)
              put    :update if parent_resource.actions.include?(:update)
              delete :destroy if parent_resource.actions.include?(:destroy)
575 576 577
            end
          end

J
Joshua Peek 已提交
578
          self
579 580
        end

J
Joshua Peek 已提交
581
        def resources(*resources, &block)
J
Joshua Peek 已提交
582
          options = resources.extract_options!
583

584
          if apply_common_behavior_for(:resources, resources, options, &block)
585 586 587
            return self
          end

588 589
          resource_scope(Resource.new(resources.pop, options)) do
            yield if block_given?
J
Joshua Peek 已提交
590

591
            collection_scope do
592 593
              get  :index if parent_resource.actions.include?(:index)
              post :create if parent_resource.actions.include?(:create)
594
            end
595

596 597
            new_scope do
              get :new
598
            end if parent_resource.actions.include?(:new)
599

600
            member_scope  do
601
              get    :edit if parent_resource.actions.include?(:edit)
602 603 604
              get    :show if parent_resource.actions.include?(:show)
              put    :update if parent_resource.actions.include?(:update)
              delete :destroy if parent_resource.actions.include?(:destroy)
605 606 607
            end
          end

J
Joshua Peek 已提交
608
          self
609 610
        end

J
Joshua Peek 已提交
611 612 613
        def collection
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use collection outside resources scope"
614 615
          end

616 617
          collection_scope do
            yield
J
Joshua Peek 已提交
618
          end
619
        end
J
Joshua Peek 已提交
620

J
Joshua Peek 已提交
621
        def member
622 623
          unless resource_scope?
            raise ArgumentError, "can't use member outside resource(s) scope"
J
Joshua Peek 已提交
624
          end
J
Joshua Peek 已提交
625

626 627
          member_scope do
            yield
628 629 630 631 632 633 634
          end
        end

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

636 637
          new_scope do
            yield
J
Joshua Peek 已提交
638
          end
J
Joshua Peek 已提交
639 640
        end

641
        def nested
642 643
          unless resource_scope?
            raise ArgumentError, "can't use nested outside resource(s) scope"
644 645 646
          end

          with_scope_level(:nested) do
647
            if shallow?
648
              with_exclusive_scope do
649
                if @scope[:shallow_path].blank?
650
                  scope(parent_resource.nested_scope, nested_options) { yield }
651
                else
652
                  scope(@scope[:shallow_path], :as => @scope[:shallow_prefix]) do
653
                    scope(parent_resource.nested_scope, nested_options) { yield }
654 655 656 657
                  end
                end
              end
            else
658
              scope(parent_resource.nested_scope, nested_options) { yield }
659 660 661 662
            end
          end
        end

663
        def namespace(path, options = {})
664
          if resource_scope?
665 666 667 668 669 670
            nested { super }
          else
            super
          end
        end

671 672 673 674 675 676
        def shallow
          scope(:shallow => true) do
            yield
          end
        end

677 678 679 680
        def shallow?
          parent_resource.instance_of?(Resource) && @scope[:shallow]
        end

J
Joshua Peek 已提交
681
        def match(*args)
682
          options = args.extract_options!.dup
683 684
          options[:anchor] = true unless options.key?(:anchor)

685
          if args.length > 1
686
            args.each { |path| match(path, options.dup) }
687 688 689
            return self
          end

690 691
          on = options.delete(:on)
          if VALID_ON_OPTIONS.include?(on)
692
            args.push(options)
693 694 695
            return send(on){ match(*args) }
          elsif on
            raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
696 697
          end

698 699
          if @scope[:scope_level] == :resource
            args.push(options)
J
Joshua Peek 已提交
700 701
            return member { match(*args) }
          end
J
Joshua Peek 已提交
702

703 704 705 706
          if resource_scope?
            raise ArgumentError, "can't define route directly in resource(s) scope"
          end

707
          action = args.first
708
          path = path_for_action(action, options.delete(:path))
709

710 711
          if action.to_s =~ /^[\w\/]+$/
            options[:action] ||= action unless action.to_s.include?("/")
712
            options[:as] = name_for_action(action, options[:as])
713 714
          else
            options[:as] = name_for_action(options[:as])
J
Joshua Peek 已提交
715
          end
J
Joshua Peek 已提交
716

717
          super(path, options)
J
Joshua Peek 已提交
718 719
        end

720
        def root(options={})
721
          if @scope[:scope_level] == :resources
722 723
            with_scope_level(:root) do
              scope(parent_resource.path) do
724 725 726 727 728 729
                super(options)
              end
            end
          else
            super(options)
          end
730 731
        end

732
        protected
733

734
          def parent_resource #:nodoc:
735 736 737
            @scope[:scope_level_resource]
          end

738
          def apply_common_behavior_for(method, resources, options, &block)
739 740 741 742 743
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

744
            options.keys.each do |k|
745 746 747
              (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp)
            end

748 749 750
            scope_options = options.slice!(*RESOURCE_OPTIONS)
            unless scope_options.empty?
              scope(scope_options) do
751 752 753 754 755
                send(method, resources.pop, options, &block)
              end
              return true
            end

756 757 758 759
            unless action_options?(options)
              options.merge!(scope_action_options) if scope_action_options?
            end

760
            if resource_scope?
761 762 763 764 765 766 767 768 769
              nested do
                send(method, resources.pop, options, &block)
              end
              return true
            end

            false
          end

770 771 772 773 774 775 776 777 778 779 780 781
          def action_options?(options)
            options[:only] || options[:except]
          end

          def scope_action_options?
            @scope[:options].is_a?(Hash) && (@scope[:options][:only] || @scope[:options][:except])
          end

          def scope_action_options
            @scope[:options].slice(:only, :except)
          end

782 783 784 785
          def resource_scope?
            [:resource, :resources].include?(@scope[:scope_level])
          end

786 787 788 789
          def resource_method_scope?
            [:collection, :member, :new].include?(@scope[:scope_level])
          end

790
          def with_exclusive_scope
791
            begin
792 793
              old_name_prefix, old_path = @scope[:as], @scope[:path]
              @scope[:as], @scope[:path] = nil, nil
794

795 796 797
              with_scope_level(:exclusive) do
                yield
              end
798
            ensure
799
              @scope[:as], @scope[:path] = old_name_prefix, old_path
800 801 802
            end
          end

803
          def with_scope_level(kind, resource = parent_resource)
J
Joshua Peek 已提交
804
            old, @scope[:scope_level] = @scope[:scope_level], kind
805
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
J
Joshua Peek 已提交
806 807 808
            yield
          ensure
            @scope[:scope_level] = old
809
            @scope[:scope_level_resource] = old_resource
J
Joshua Peek 已提交
810
          end
811 812 813

          def resource_scope(resource)
            with_scope_level(resource.is_a?(SingletonResource) ? :resource : :resources, resource) do
814
              scope(parent_resource.resource_scope) do
815 816 817 818 819
                yield
              end
            end
          end

820 821
          def new_scope
            with_scope_level(:new) do
822
              scope(parent_resource.new_scope(action_path(:new))) do
823 824 825 826 827
                yield
              end
            end
          end

828 829
          def collection_scope
            with_scope_level(:collection) do
830
              scope(parent_resource.collection_scope) do
831 832 833 834 835 836 837
                yield
              end
            end
          end

          def member_scope
            with_scope_level(:member) do
838
              scope(parent_resource.member_scope) do
839 840 841 842 843
                yield
              end
            end
          end

844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
          def nested_options
            {}.tap do |options|
              options[:as] = parent_resource.member_name
              options[:constraints] = { "#{parent_resource.singular}_id".to_sym => id_constraint } if id_constraint?
            end
          end

          def id_constraint?
            @scope[:id].is_a?(Regexp) || (@scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp))
          end

          def id_constraint
            @scope[:id] || @scope[:constraints][:id]
          end

859
          def canonical_action?(action, flag)
860
            flag && resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s)
861 862 863
          end

          def shallow_scoping?
864
            shallow? && @scope[:scope_level] == :member
865 866
          end

867
          def path_for_action(action, path)
868
            prefix = shallow_scoping? ?
869 870
              "#{@scope[:shallow_path]}/#{parent_resource.path}/:id" : @scope[:path]

871 872
            path = if canonical_action?(action, path.blank?)
              prefix.to_s
873
            else
874
              "#{prefix}/#{action_path(action, path)}"
875 876 877
            end
          end

878 879
          def action_path(name, path = nil)
            path || @scope[:path_names][name.to_sym] || name.to_s
880 881
          end

882 883
          def prefix_name_for_action(action, as)
            if as.present?
884
              as.to_s
885
            elsif as
886
              nil
887
            elsif !canonical_action?(action, @scope[:scope_level])
888
              action.to_s
889
            end
890 891
          end

892 893
          def name_for_action(action, as=nil)
            prefix = prefix_name_for_action(action, as)
894
            prefix = Mapper.normalize_name(prefix) if prefix
895 896 897 898 899
            name_prefix = @scope[:as]

            if parent_resource
              collection_name = parent_resource.collection_name
              member_name = parent_resource.member_name
900
            end
901

902
            name = case @scope[:scope_level]
903
            when :collection
904
              [prefix, name_prefix, collection_name]
905
            when :new
906 907 908 909 910
              [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]
911
            else
912
              [name_prefix, member_name, prefix]
913
            end
914

915
            name.select(&:present?).join("_").presence
916
          end
J
Joshua Peek 已提交
917
      end
J
Joshua Peek 已提交
918

919 920 921 922 923 924 925 926 927 928 929 930 931
      module Shorthand
        def match(*args)
          if args.size == 1 && args.last.is_a?(Hash)
            options  = args.pop
            path, to = options.find { |name, value| name.is_a?(String) }
            options.merge!(:to => to).delete(path)
            super(path, options)
          else
            super
          end
        end
      end

932 933 934 935
      include Base
      include HttpHelpers
      include Scoping
      include Resources
936
      include Shorthand
J
Joshua Peek 已提交
937 938
    end
  end
J
Joshua Peek 已提交
939
end