mapper.rb 28.1 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(req)
J
Joshua Peek 已提交
30
              return [ 404, {'X-Cascade' => 'pass'}, [] ]
31 32 33 34 35 36 37
            end
          }

          @app.call(env)
        end
      end

38
      class Mapping #:nodoc:
39
        IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix]
40

41 42 43
        def initialize(set, scope, args)
          @set, @scope    = set, scope
          @path, @options = extract_path_and_options(args)
44
          normalize_options!
45
        end
J
Joshua Peek 已提交
46

47
        def to_route
48
          [ app, conditions, requirements, defaults, @options[:as], @options[:anchor] ]
49
        end
J
Joshua Peek 已提交
50

51 52
        private
          def extract_path_and_options(args)
53
            options = args.extract_options!
54

55
            if using_to_shorthand?(args, options)
56 57 58 59 60
              path, to = options.find { |name, value| name.is_a?(String) }
              options.merge!(:to => to).delete(path) if path
            else
              path = args.first
            end
J
Joshua Peek 已提交
61

62 63 64 65 66 67 68 69 70 71
            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

72 73 74 75 76
            [ normalize_path(path), options ]
          end

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

78 79 80 81
            if using_match_shorthand?(path_without_format, @options)
              to_shorthand    = @options[:to].blank?
              @options[:to] ||= path_without_format[1..-1].sub(%r{/([^/]*)$}, '#\1')
              @options[:as] ||= path_without_format[1..-1].gsub("/", "_")
82 83
            end

84
            @options.merge!(default_controller_and_action(to_shorthand))
85
          end
86

87 88 89 90
          # match "account" => "account#index"
          def using_to_shorthand?(args, options)
            args.empty? && options.present?
          end
91

92
          # match "account/overview"
93
          def using_match_shorthand?(path, options)
94
            path && options.except(:via, :anchor, :to, :as).empty? && path =~ %r{^/[\w\/]+$}
95
          end
96

97
          def normalize_path(path)
98 99
            raise ArgumentError, "path is required" if @scope[:path].blank? && path.blank?
            Mapper.normalize_path("#{@scope[:path]}/#{path}")
100
          end
101

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

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

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

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

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

138 139
              controller ||= default_controller
              action     ||= default_action
140

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

145 146
              controller = controller.to_s unless controller.is_a?(Regexp)
              action     = action.to_s     unless action.is_a?(Regexp)
147

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

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

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

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

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

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

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

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

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

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

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

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

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

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

231
        def match(*args)
232 233
          mapping = Mapping.new(@set, @scope, args).to_route
          @set.add_route(*mapping)
234 235
          self
        end
236

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

          match(path, options.merge(:to => app, :anchor => false))
          self
        end

252 253 254 255
        def default_url_options=(options)
          @set.default_url_options = options
        end
        alias_method :default_url_options, :default_url_options=
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
      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

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

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

          lambda do |env|
283
            req = Request.new(env)
284 285 286 287 288

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

            uri = URI.parse(path_proc.call(*params))
289 290
            uri.scheme ||= req.scheme
            uri.host   ||= req.host
291
            uri.port   ||= req.port unless req.port == 80
292

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

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

301
            [ status, headers, [body] ]
302
          end
303 304 305 306 307 308 309 310 311 312 313 314 315
        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
316
        def initialize(*args) #:nodoc:
317 318 319 320 321 322
          @scope = {}
          super
        end

        def scope(*args)
          options = args.extract_options!
323
          options = options.dup
324

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

330 331 332 333 334 335 336
          case args.first
          when String
            options[:path] = args.first
          when Symbol
            options[:controller] = args.first
          end

337
          recover = {}
338

339 340 341
          options[:constraints] ||= {}
          unless options[:constraints].is_a?(Hash)
            block, options[:constraints] = options[:constraints], {}
342
          end
343

344 345 346 347 348
          scope_options.each do |option|
            if value = options.delete(option)
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
349 350
          end

351 352
          recover[:block] = @scope[:blocks]
          @scope[:blocks] = merge_blocks_scope(@scope[:blocks], block)
353

354 355
          recover[:options] = @scope[:options]
          @scope[:options]  = merge_options_scope(@scope[:options], options)
356 357 358 359

          yield
          self
        ensure
360 361 362 363 364 365
          scope_options.each do |option|
            @scope[option] = recover[option] if recover.has_key?(option)
          end

          @scope[:options] = recover[:options]
          @scope[:blocks]  = recover[:block]
366 367 368 369 370 371
        end

        def controller(controller)
          scope(controller.to_sym) { yield }
        end

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

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

383 384 385 386
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

387 388 389 390 391
        def match(*args)
          options = args.extract_options!

          options = (@scope[:options] || {}).merge(options)

392 393 394 395
          if @scope[:as] && !options[:as].blank?
            options[:as] = "#{@scope[:as]}_#{options[:as]}"
          elsif @scope[:as] && options[:as] == ""
            options[:as] = @scope[:as].to_s
396 397 398 399 400
          end

          args.push(options)
          super(*args)
        end
401 402 403 404 405 406 407

        private
          def scope_options
            @scope_options ||= private_methods.grep(/^merge_(.+)_scope$/) { $1.to_sym }
          end

          def merge_path_scope(parent, child)
408
            Mapper.normalize_path("#{parent}/#{child}")
409 410
          end

411 412 413 414
          def merge_shallow_path_scope(parent, child)
            Mapper.normalize_path("#{parent}/#{child}")
          end

415
          def merge_as_scope(parent, child)
416
            parent ? "#{parent}_#{child}" : child
417 418
          end

419 420 421 422
          def merge_shallow_prefix_scope(parent, child)
            parent ? "#{parent}_#{child}" : child
          end

423
          def merge_module_scope(parent, child)
424 425 426 427
            parent ? "#{parent}/#{child}" : child
          end

          def merge_controller_scope(parent, child)
428
            child
429 430
          end

431
          def merge_path_names_scope(parent, child)
432 433 434 435 436 437 438
            merge_options_scope(parent, child)
          end

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

439 440 441 442
          def merge_defaults_scope(parent, child)
            merge_options_scope(parent, child)
          end

443
          def merge_blocks_scope(parent, child)
444 445 446
            merged = parent ? parent.dup : []
            merged << child if child
            merged
447 448 449
          end

          def merge_options_scope(parent, child)
450
            (parent || {}).except(*override_keys(child)).merge(child)
451
          end
452 453 454 455

          def merge_shallow_scope(parent, child)
            child ? true : false
          end
456 457 458 459

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

J
Joshua Peek 已提交
462
      module Resources
463 464 465 466
        # CANONICAL_ACTIONS holds all actions that does not need a prefix or
        # a path appended since they fit properly in their scope level.
        VALID_ON_OPTIONS = [:new, :collection, :member]
        CANONICAL_ACTIONS = [:index, :create, :new, :show, :update, :destroy]
467
        RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except]
468

469
        class Resource #:nodoc:
470
          DEFAULT_ACTIONS = [:index, :create, :new, :show, :update, :destroy, :edit]
471

472
          attr_reader :controller, :path, :options
473 474

          def initialize(entities, options = {})
475 476
            @name       = entities.to_s
            @path       = options.delete(:path) || @name
477
            @controller = (options.delete(:controller) || @name).to_s
478
            @as         = options.delete(:as)
479
            @options    = options
480 481
          end

482
          def default_actions
483
            self.class::DEFAULT_ACTIONS
484 485
          end

486 487 488 489 490 491 492 493 494 495
          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

496
          def name
497
            @as || @name
498 499
          end

500
          def plural
501
            @plural ||= name.to_s
502 503 504
          end

          def singular
505
            @singular ||= name.to_s.singularize
506 507
          end

508
          alias :member_name :singular
509

510
          # Checks for uncountable plurals, and appends "_index" if they're.
511
          def collection_name
512
            singular == plural ? "#{plural}_index" : plural
513 514
          end

515
          def resource_scope
516
            { :controller => controller }
517 518
          end

519
          alias :collection_scope :path
520 521

          def member_scope
522
            "#{path}/:id"
523 524
          end

525
          def new_scope(new_path)
526
            "#{path}/#{new_path}"
527 528 529
          end

          def nested_scope
530
            "#{path}/:#{singular}_id"
531
          end
532

533 534 535
        end

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

538 539 540
          def initialize(entities, options)
            @name       = entities.to_s
            @path       = options.delete(:path) || @name
541
            @controller = (options.delete(:controller) || plural).to_s
542 543 544 545
            @as         = options.delete(:as)
            @options    = options
          end

546 547
          def plural
            @plural ||= name.to_s.pluralize
548 549
          end

550 551
          def singular
            @singular ||= name.to_s
552
          end
553 554 555 556 557 558

          alias :member_name :singular
          alias :collection_name :singular

          alias :member_scope :path
          alias :nested_scope :path
559 560
        end

561
        def initialize(*args) #:nodoc:
562
          super
563
          @scope[:path_names] = @set.resources_path_names
564 565
        end

566 567 568 569
        def resources_path_names(options)
          @scope[:path_names].merge!(options)
        end

J
Joshua Peek 已提交
570
        def resource(*resources, &block)
J
Joshua Peek 已提交
571
          options = resources.extract_options!
J
Joshua Peek 已提交
572

573
          if apply_common_behavior_for(:resource, resources, options, &block)
574 575 576
            return self
          end

577 578
          resource_scope(SingletonResource.new(resources.pop, options)) do
            yield if block_given?
579

580
            collection_scope do
581
              post :create
582
            end if parent_resource.actions.include?(:create)
583 584 585

            new_scope do
              get :new
586
            end if parent_resource.actions.include?(:new)
587

588
            member_scope  do
589 590 591 592
              get    :show if parent_resource.actions.include?(:show)
              put    :update if parent_resource.actions.include?(:update)
              delete :destroy if parent_resource.actions.include?(:destroy)
              get    :edit if parent_resource.actions.include?(:edit)
593 594 595
            end
          end

J
Joshua Peek 已提交
596
          self
597 598
        end

J
Joshua Peek 已提交
599
        def resources(*resources, &block)
J
Joshua Peek 已提交
600
          options = resources.extract_options!
601

602
          if apply_common_behavior_for(:resources, resources, options, &block)
603 604 605
            return self
          end

606 607
          resource_scope(Resource.new(resources.pop, options)) do
            yield if block_given?
J
Joshua Peek 已提交
608

609
            collection_scope do
610 611
              get  :index if parent_resource.actions.include?(:index)
              post :create if parent_resource.actions.include?(:create)
612
            end
613

614 615
            new_scope do
              get :new
616
            end if parent_resource.actions.include?(:new)
617

618
            member_scope  do
619 620 621 622
              get    :show if parent_resource.actions.include?(:show)
              put    :update if parent_resource.actions.include?(:update)
              delete :destroy if parent_resource.actions.include?(:destroy)
              get    :edit if parent_resource.actions.include?(:edit)
623 624 625
            end
          end

J
Joshua Peek 已提交
626
          self
627 628
        end

J
Joshua Peek 已提交
629 630 631
        def collection
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use collection outside resources scope"
632 633
          end

634 635
          collection_scope do
            yield
J
Joshua Peek 已提交
636
          end
637
        end
J
Joshua Peek 已提交
638

J
Joshua Peek 已提交
639
        def member
640 641
          unless resource_scope?
            raise ArgumentError, "can't use member outside resource(s) scope"
J
Joshua Peek 已提交
642
          end
J
Joshua Peek 已提交
643

644 645
          member_scope do
            yield
646 647 648 649 650 651 652
          end
        end

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

654 655
          new_scope do
            yield
J
Joshua Peek 已提交
656
          end
J
Joshua Peek 已提交
657 658
        end

659
        def nested
660 661
          unless resource_scope?
            raise ArgumentError, "can't use nested outside resource(s) scope"
662 663 664
          end

          with_scope_level(:nested) do
665
            if shallow?
666
              with_exclusive_scope do
667
                if @scope[:shallow_path].blank?
668
                  scope(parent_resource.nested_scope, nested_options) { yield }
669
                else
670
                  scope(@scope[:shallow_path], :as => @scope[:shallow_prefix]) do
671
                    scope(parent_resource.nested_scope, nested_options) { yield }
672 673 674 675
                  end
                end
              end
            else
676
              scope(parent_resource.nested_scope, nested_options) { yield }
677 678 679 680
            end
          end
        end

681
        def namespace(path, options = {})
682
          if resource_scope?
683 684 685 686 687 688
            nested { super }
          else
            super
          end
        end

689 690 691 692 693 694
        def shallow
          scope(:shallow => true) do
            yield
          end
        end

695 696 697 698
        def shallow?
          parent_resource.instance_of?(Resource) && @scope[:shallow]
        end

J
Joshua Peek 已提交
699
        def match(*args)
700
          options = args.extract_options!.dup
701 702
          options[:anchor] = true unless options.key?(:anchor)

703
          if args.length > 1
704
            args.each { |path| match(path, options.dup) }
705 706 707
            return self
          end

708 709
          on = options.delete(:on)
          if VALID_ON_OPTIONS.include?(on)
710
            args.push(options)
711 712 713
            return send(on){ match(*args) }
          elsif on
            raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
714 715
          end

716 717
          if @scope[:scope_level] == :resource
            args.push(options)
J
Joshua Peek 已提交
718 719
            return member { match(*args) }
          end
J
Joshua Peek 已提交
720

721
          path = options.delete(:path)
722
          action = args.first
723

724 725 726 727
          if action.is_a?(Symbol)
            path = path_for_action(action, path)
            options[:to] ||= action
            options[:as]   = name_for_action(action, options[:as])
728 729

            with_exclusive_scope do
730 731 732 733
              return super(path, options)
            end
          elsif resource_method_scope?
            path = path_for_custom_action
734
            options[:action] ||= action
735 736 737 738 739 740 741
            options[:as] = name_for_action(options[:as]) if options[:as]
            args.push(options)

            with_exclusive_scope do
              scope(path) do
                return super
              end
742
            end
743 744 745 746
          end

          if resource_scope?
            raise ArgumentError, "can't define route directly in resource(s) scope"
J
Joshua Peek 已提交
747
          end
J
Joshua Peek 已提交
748

749
          args.push(options)
J
Joshua Peek 已提交
750
          super
J
Joshua Peek 已提交
751 752
        end

753
        def root(options={})
754
          if @scope[:scope_level] == :resources
755
            with_scope_level(:nested) do
756
              scope(parent_resource.path, :as => parent_resource.collection_name) do
757 758 759 760 761 762
                super(options)
              end
            end
          else
            super(options)
          end
763 764
        end

765
        protected
766

767
          def parent_resource #:nodoc:
768 769 770
            @scope[:scope_level_resource]
          end

771
          def apply_common_behavior_for(method, resources, options, &block)
772 773 774 775 776
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

777 778 779
            scope_options = options.slice!(*RESOURCE_OPTIONS)
            unless scope_options.empty?
              scope(scope_options) do
780 781 782 783 784
                send(method, resources.pop, options, &block)
              end
              return true
            end

785 786 787 788
            unless action_options?(options)
              options.merge!(scope_action_options) if scope_action_options?
            end

789
            if resource_scope?
790 791 792 793 794 795 796 797 798
              nested do
                send(method, resources.pop, options, &block)
              end
              return true
            end

            false
          end

799 800 801 802 803 804 805 806 807 808 809 810
          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

811 812 813 814
          def resource_scope?
            [:resource, :resources].include?(@scope[:scope_level])
          end

815 816 817 818
          def resource_method_scope?
            [:collection, :member, :new].include?(@scope[:scope_level])
          end

819
          def with_exclusive_scope
820
            begin
821 822
              old_name_prefix, old_path = @scope[:as], @scope[:path]
              @scope[:as], @scope[:path] = nil, nil
823

824 825 826
              with_scope_level(:exclusive) do
                yield
              end
827
            ensure
828
              @scope[:as], @scope[:path] = old_name_prefix, old_path
829 830 831
            end
          end

832
          def with_scope_level(kind, resource = parent_resource)
J
Joshua Peek 已提交
833
            old, @scope[:scope_level] = @scope[:scope_level], kind
834
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
J
Joshua Peek 已提交
835 836 837
            yield
          ensure
            @scope[:scope_level] = old
838
            @scope[:scope_level_resource] = old_resource
J
Joshua Peek 已提交
839
          end
840 841 842

          def resource_scope(resource)
            with_scope_level(resource.is_a?(SingletonResource) ? :resource : :resources, resource) do
843
              scope(parent_resource.resource_scope) do
844 845 846 847 848
                yield
              end
            end
          end

849 850
          def new_scope
            with_scope_level(:new) do
851
              scope(parent_resource.new_scope(action_path(:new))) do
852 853 854 855 856
                yield
              end
            end
          end

857 858
          def collection_scope
            with_scope_level(:collection) do
859
              scope(parent_resource.collection_scope) do
860 861 862 863 864 865 866
                yield
              end
            end
          end

          def member_scope
            with_scope_level(:member) do
867
              scope(parent_resource.member_scope) do
868 869 870 871 872
                yield
              end
            end
          end

873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
          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

888 889 890 891 892
          def canonical_action?(action, flag)
            flag && CANONICAL_ACTIONS.include?(action)
          end

          def shallow_scoping?
893
            shallow? && @scope[:scope_level] == :member
894 895
          end

896
          def path_for_action(action, path)
897
            prefix = shallow_scoping? ?
898 899
              "#{@scope[:shallow_path]}/#{parent_resource.path}/:id" : @scope[:path]

900
            if canonical_action?(action, path.blank?)
901
              "#{prefix}(.:format)"
902
            else
903
              "#{prefix}/#{action_path(action, path)}(.:format)"
904 905 906
            end
          end

907
          def path_for_custom_action
908 909
            if shallow_scoping?
              "#{@scope[:shallow_path]}/#{parent_resource.path}/:id"
910
            else
911
              @scope[:path]
912 913 914
            end
          end

915 916
          def action_path(name, path = nil)
            path || @scope[:path_names][name.to_sym] || name.to_s
917 918
          end

919 920 921 922 923 924 925 926
          def prefix_name_for_action(action, as)
            if as.present?
              "#{as}_"
            elsif as
              ""
            elsif !canonical_action?(action, @scope[:scope_level])
              "#{action}_"
            end
927 928
          end

929 930 931 932 933 934 935 936
          def name_for_action(action, as=nil)
            prefix = prefix_name_for_action(action, as)
            name_prefix = @scope[:as]

            if parent_resource
              collection_name = parent_resource.collection_name
              member_name = parent_resource.member_name
              name_prefix = "#{name_prefix}_" if name_prefix.present?
937
            end
938

939 940
            case @scope[:scope_level]
            when :collection
941
              "#{prefix}#{name_prefix}#{collection_name}"
942
            when :new
943
              "#{prefix}new_#{name_prefix}#{member_name}"
944
            else
945
              if shallow_scoping?
946
                shallow_prefix = "#{@scope[:shallow_prefix]}_" if @scope[:shallow_prefix].present?
947
                "#{prefix}#{shallow_prefix}#{member_name}"
948
              else
949
                "#{prefix}#{name_prefix}#{member_name}"
950 951 952
              end
            end
          end
J
Joshua Peek 已提交
953
      end
J
Joshua Peek 已提交
954

955 956 957 958
      include Base
      include HttpHelpers
      include Scoping
      include Resources
J
Joshua Peek 已提交
959 960
    end
  end
J
Joshua Peek 已提交
961
end