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

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

16 17
        def initialize(app, constraints, request)
          @app, @constraints, @request = app, constraints, request
18 19 20
        end

        def call(env)
21
          req = @request.new(env)
22 23 24

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

          @app.call(env)
        end
      end

35
      class Mapping #:nodoc:
36 37
        IGNORE_OPTIONS = [:to, :as, :controller, :action, :via, :on, :constraints, :defaults, :only, :except, :anchor]

38 39 40
        def initialize(set, scope, args)
          @set, @scope    = set, scope
          @path, @options = extract_path_and_options(args)
41
        end
J
Joshua Peek 已提交
42

43
        def to_route
44
          [ app, conditions, requirements, defaults, @options[:as], @options[:anchor] ]
45
        end
J
Joshua Peek 已提交
46

47 48
        private
          def extract_path_and_options(args)
49
            options = args.extract_options!
50

51
            if using_to_shorthand?(args, options)
52 53 54 55 56
              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 已提交
57

58 59 60
            path = normalize_path(path)

            if using_match_shorthand?(path, options)
61 62
              options[:to] ||= path[1..-1].sub(%r{/([^/]*)$}, '#\1')
              options[:as] ||= path[1..-1].gsub("/", "_")
63 64 65
            end

            [ path, options ]
66
          end
67

68 69 70 71
          # match "account" => "account#index"
          def using_to_shorthand?(args, options)
            args.empty? && options.present?
          end
72

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

78
          def normalize_path(path)
79 80
            raise ArgumentError, "path is required" if @scope[:path].blank? && path.blank?
            Mapper.normalize_path("#{@scope[:path]}/#{path}")
81
          end
82

83 84 85
          def app
            Constraints.new(
              to.respond_to?(:call) ? to : Routing::RouteSet::Dispatcher.new(:defaults => defaults),
86 87
              blocks,
              @set.request_class
88
            )
89 90
          end

91 92 93
          def conditions
            { :path_info => @path }.merge(constraints).merge(request_method_condition)
          end
J
Joshua Peek 已提交
94

95
          def requirements
96
            @requirements ||= (@options[:constraints] || {}).tap do |requirements|
97 98 99 100
              requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints]
              @options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) }
            end
          end
101

102
          def defaults
103 104 105 106 107 108 109 110 111
            @defaults ||= (@options[:defaults] || {}).tap do |defaults|
              defaults.merge!(default_controller_and_action)
              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

          def default_controller_and_action
            if to.respond_to?(:call)
112 113 114 115 116 117 118
              { }
            else
              defaults = case to
              when String
                controller, action = to.split('#')
                { :controller => controller, :action => action }
              when Symbol
119
                { :action => to.to_s }.merge(default_controller ? { :controller => default_controller } : {})
120
              else
121
                default_controller ? { :controller => default_controller } : {}
122
              end
J
Joshua Peek 已提交
123

124 125 126
              if defaults[:controller].blank? && segment_keys.exclude?("controller")
                raise ArgumentError, "missing :controller"
              end
J
Joshua Peek 已提交
127

128 129 130
              if defaults[:action].blank? && segment_keys.exclude?("action")
                raise ArgumentError, "missing :action"
              end
J
Joshua Peek 已提交
131

132 133 134
              defaults
            end
          end
135

136 137 138 139 140 141
          def blocks
            if @options[:constraints].present? && !@options[:constraints].is_a?(Hash)
              block = @options[:constraints]
            else
              block = nil
            end
J
Joshua Peek 已提交
142 143

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

146 147 148
          def constraints
            @constraints ||= requirements.reject { |k, v| segment_keys.include?(k.to_s) || k == :controller }
          end
149

150 151 152 153 154 155
          def request_method_condition
            if via = @options[:via]
              via = Array(via).map { |m| m.to_s.upcase }
              { :request_method => Regexp.union(*via) }
            else
              { }
156
            end
157
          end
J
Joshua Peek 已提交
158

159 160
          def segment_keys
            @segment_keys ||= Rack::Mount::RegexpWithNamedGroups.new(
161 162
              Rack::Mount::Strexp.compile(@path, requirements, SEPARATORS)
            ).names
163
          end
164

165 166 167
          def to
            @options[:to]
          end
J
Joshua Peek 已提交
168

169 170
          def default_controller
            @scope[:controller].to_s if @scope[:controller]
171
          end
172
      end
173

174
      # Invokes Rack::Mount::Utils.normalize path and ensure that
175 176
      # (:locale) becomes (/:locale) instead of /(:locale). Except
      # for root cases, where the latter is the correct one.
177 178
      def self.normalize_path(path)
        path = Rack::Mount::Utils.normalize_path(path)
179
        path.sub!(%r{/(\(+)/?:}, '\1/:') unless path =~ %r{^/\(+:.*\)$}
180 181 182
        path
      end

183
      module Base
184
        def initialize(set) #:nodoc:
185 186
          @set = set
        end
187

188 189 190
        def root(options = {})
          match '/', options.reverse_merge(:as => :root)
        end
191

192
        def match(*args)
193 194
          mapping = Mapping.new(@set, @scope, args).to_route
          @set.add_route(*mapping)
195 196
          self
        end
197

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
        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

213 214 215 216
        def default_url_options=(options)
          @set.default_url_options = options
        end
        alias_method :default_url_options, :default_url_options=
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
      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

236 237 238
        def redirect(*args, &block)
          options = args.last.is_a?(Hash) ? args.pop : {}

239 240 241
          path      = args.shift || block
          path_proc = path.is_a?(Proc) ? path : proc { |params| path % params }
          status    = options[:status] || 301
242
          body      = 'Moved Permanently'
243 244

          lambda do |env|
245
            req = Request.new(env)
246 247 248 249 250

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

            uri = URI.parse(path_proc.call(*params))
251 252
            uri.scheme ||= req.scheme
            uri.host   ||= req.host
253
            uri.port   ||= req.port unless req.port == 80
254 255 256 257 258 259 260

            headers = {
              'Location' => uri.to_s,
              'Content-Type' => 'text/html',
              'Content-Length' => body.length.to_s
            }
            [ status, headers, [body] ]
261
          end
262 263 264 265 266 267 268 269 270 271 272 273 274
        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
275
        def initialize(*args) #:nodoc:
276 277 278 279 280 281
          @scope = {}
          super
        end

        def scope(*args)
          options = args.extract_options!
282
          options = options.dup
283 284 285 286 287 288 289 290

          case args.first
          when String
            options[:path] = args.first
          when Symbol
            options[:controller] = args.first
          end

291
          recover = {}
292

293 294 295
          options[:constraints] ||= {}
          unless options[:constraints].is_a?(Hash)
            block, options[:constraints] = options[:constraints], {}
296
          end
297

298 299 300 301 302
          scope_options.each do |option|
            if value = options.delete(option)
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
303 304
          end

305 306
          recover[:block] = @scope[:blocks]
          @scope[:blocks] = merge_blocks_scope(@scope[:blocks], block)
307

308 309
          recover[:options] = @scope[:options]
          @scope[:options]  = merge_options_scope(@scope[:options], options)
310 311 312 313

          yield
          self
        ensure
314 315 316 317 318 319
          scope_options.each do |option|
            @scope[option] = recover[option] if recover.has_key?(option)
          end

          @scope[:options] = recover[:options]
          @scope[:blocks]  = recover[:block]
320 321 322 323 324 325
        end

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

326 327 328
        def namespace(path)
          path = path.to_s
          scope(:path => path, :name_prefix => path, :module => path) { yield }
329 330 331 332 333 334
        end

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

335 336 337 338
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

339 340 341 342 343
        def match(*args)
          options = args.extract_options!

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

344 345
          if @scope[:name_prefix] && !options[:as].blank?
            options[:as] = "#{@scope[:name_prefix]}_#{options[:as]}"
346
          elsif @scope[:name_prefix] && options[:as] == ""
347
            options[:as] = @scope[:name_prefix].to_s
348 349 350 351 352
          end

          args.push(options)
          super(*args)
        end
353 354 355 356 357 358 359

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

          def merge_path_scope(parent, child)
360
            Mapper.normalize_path("#{parent}/#{child}")
361 362 363 364 365 366
          end

          def merge_name_prefix_scope(parent, child)
            parent ? "#{parent}_#{child}" : child
          end

367
          def merge_module_scope(parent, child)
368 369 370 371
            parent ? "#{parent}/#{child}" : child
          end

          def merge_controller_scope(parent, child)
372
            @scope[:module] ? "#{@scope[:module]}/#{child}" : child
373 374
          end

375
          def merge_path_names_scope(parent, child)
376 377 378 379 380 381 382
            merge_options_scope(parent, child)
          end

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

383 384 385 386
          def merge_defaults_scope(parent, child)
            merge_options_scope(parent, child)
          end

387 388 389 390 391 392 393
          def merge_blocks_scope(parent, child)
            (parent || []) + [child]
          end

          def merge_options_scope(parent, child)
            (parent || {}).merge(child)
          end
394 395
      end

J
Joshua Peek 已提交
396
      module Resources
397
        CRUD_ACTIONS = [:index, :show, :create, :update, :destroy] #:nodoc:
398

399
        class Resource #:nodoc:
400 401 402 403
          def self.default_actions
            [:index, :create, :new, :show, :update, :destroy, :edit]
          end

404
          attr_reader :controller, :path, :options
405 406

          def initialize(entities, options = {})
407 408 409 410
            @name       = entities.to_s
            @path       = options.delete(:path) || @name
            @controller = options.delete(:controller) || @name.to_s.pluralize
            @options    = options
411 412
          end

413 414 415 416 417 418
          def default_actions
            self.class.default_actions
          end

          def actions
            if only = options[:only]
419
              Array(only).map(&:to_sym)
420
            elsif except = options[:except]
421
              default_actions - Array(except).map(&:to_sym)
422 423 424 425 426
            else
              default_actions
            end
          end

427 428 429 430 431 432 433 434 435
          def action_type(action)
            case action
            when :index, :create
              :collection
            when :show, :update, :destroy
              :member
            end
          end

436
          def name
437
            options[:as] || @name
438 439
          end

440 441 442 443 444 445
          def plural
            name.to_s.pluralize
          end

          def singular
            name.to_s.singularize
446 447 448
          end

          def member_name
449
            singular
450 451
          end

452
          # Checks for uncountable plurals, and appends "_index" if they're.
453
          def collection_name
454 455
            uncountable? ? "#{plural}_index" : plural
          end
456

457 458
          def uncountable?
            singular == plural
459
          end
460

461 462 463 464 465 466 467 468 469
          def name_for_action(action)
            case action_type(action)
            when :collection
              collection_name
            when :member
              member_name
            end
          end

470 471 472
          def id_segment
            ":#{singular}_id"
          end
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498

          def constraints
            options[:constraints] || {}
          end

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

          def id_constraint
            options[:id] || constraints[:id]
          end

          def collection_options
            (options || {}).dup.tap do |options|
              options.delete(:id)
              options[:constraints] = options[:constraints].dup if options[:constraints]
              options[:constraints].delete(:id) if options[:constraints].is_a?(Hash)
            end
          end

          def nested_options
            options = { :name_prefix => member_name }
            options["#{singular}_id".to_sym] = id_constraint if id_constraint?
            options
          end
499 500 501
        end

        class SingletonResource < Resource #:nodoc:
502 503 504 505
          def self.default_actions
            [:show, :create, :update, :destroy, :new, :edit]
          end

506
          def initialize(entity, options = {})
507
            super
508 509
          end

510 511 512 513 514 515 516
          def action_type(action)
            case action
            when :show, :create, :update, :destroy
              :member
            end
          end

517 518
          def member_name
            name
519 520 521
          end
        end

522
        def initialize(*args) #:nodoc:
523
          super
524
          @scope[:path_names] = @set.resources_path_names
525 526
        end

J
Joshua Peek 已提交
527
        def resource(*resources, &block)
J
Joshua Peek 已提交
528
          options = resources.extract_options!
J
Joshua Peek 已提交
529

530
          if apply_common_behavior_for(:resource, resources, options, &block)
531 532 533
            return self
          end

534
          resource = SingletonResource.new(resources.pop, options)
535

536
          scope(:path => resource.path, :controller => resource.controller) do
537
            with_scope_level(:resource, resource) do
538

539
              scope(:name_prefix => resource.name.to_s, :as => "") do
540 541
                yield if block_given?
              end
542

543 544 545 546 547 548 549 550
              scope(resource.options) do
                get    :show if resource.actions.include?(:show)
                post   :create if resource.actions.include?(:create)
                put    :update if resource.actions.include?(:update)
                delete :destroy if resource.actions.include?(:destroy)
                get    :new, :as => resource.name if resource.actions.include?(:new)
                get    :edit, :as => resource.name if resource.actions.include?(:edit)
              end
551 552 553
            end
          end

J
Joshua Peek 已提交
554
          self
555 556
        end

J
Joshua Peek 已提交
557
        def resources(*resources, &block)
J
Joshua Peek 已提交
558
          options = resources.extract_options!
559

560
          if apply_common_behavior_for(:resources, resources, options, &block)
561 562 563
            return self
          end

564
          resource = Resource.new(resources.pop, options)
565

566
          scope(:path => resource.path, :controller => resource.controller) do
567 568
            with_scope_level(:resources, resource) do
              yield if block_given?
J
Joshua Peek 已提交
569

570
              with_scope_level(:collection) do
571 572 573 574 575
                scope(resource.collection_options) do
                  get  :index if resource.actions.include?(:index)
                  post :create if resource.actions.include?(:create)
                  get  :new, :as => resource.singular if resource.actions.include?(:new)
                end
576
              end
577

578
              with_scope_level(:member) do
579
                scope(':id') do
580 581 582 583 584 585
                  scope(resource.options) do
                    get    :show if resource.actions.include?(:show)
                    put    :update if resource.actions.include?(:update)
                    delete :destroy if resource.actions.include?(:destroy)
                    get    :edit, :as => resource.singular if resource.actions.include?(:edit)
                  end
J
Joshua Peek 已提交
586
                end
587 588 589 590
              end
            end
          end

J
Joshua Peek 已提交
591
          self
592 593
        end

J
Joshua Peek 已提交
594 595 596
        def collection
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use collection outside resources scope"
597 598
          end

J
Joshua Peek 已提交
599
          with_scope_level(:collection) do
600
            scope(:name_prefix => parent_resource.collection_name, :as => "") do
601 602
              yield
            end
J
Joshua Peek 已提交
603
          end
604
        end
J
Joshua Peek 已提交
605

J
Joshua Peek 已提交
606 607 608 609
        def member
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use member outside resources scope"
          end
J
Joshua Peek 已提交
610

J
Joshua Peek 已提交
611
          with_scope_level(:member) do
612
            scope(':id', :name_prefix => parent_resource.member_name, :as => "") do
J
Joshua Peek 已提交
613 614 615
              yield
            end
          end
J
Joshua Peek 已提交
616 617
        end

618 619 620 621 622 623
        def nested
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use nested outside resources scope"
          end

          with_scope_level(:nested) do
624
            scope(parent_resource.id_segment, parent_resource.nested_options) do
625 626 627 628 629
              yield
            end
          end
        end

J
Joshua Peek 已提交
630
        def match(*args)
J
Joshua Peek 已提交
631
          options = args.extract_options!
632

633 634
          options[:anchor] = true unless options.key?(:anchor)

635 636 637 638 639
          if args.length > 1
            args.each { |path| match(path, options) }
            return self
          end

640
          path_names = options.delete(:path_names)
641

642
          if args.first.is_a?(Symbol)
643 644
            action = args.first
            if CRUD_ACTIONS.include?(action)
645 646 647
              begin
                old_path = @scope[:path]
                @scope[:path] = "#{@scope[:path]}(.:format)"
648 649 650 651
                return match(options.reverse_merge(
                  :to => action,
                  :as => parent_resource.name_for_action(action)
                ))
652 653 654
              ensure
                @scope[:path] = old_path
              end
655 656
            else
              with_exclusive_name_prefix(action) do
657
                return match("#{action_path(action, path_names)}(.:format)", options.reverse_merge(:to => action))
658
              end
659 660 661
            end
          end

J
Joshua Peek 已提交
662
          args.push(options)
J
Joshua Peek 已提交
663

J
Joshua Peek 已提交
664 665 666 667 668 669
          case options.delete(:on)
          when :collection
            return collection { match(*args) }
          when :member
            return member { match(*args) }
          end
J
Joshua Peek 已提交
670

J
Joshua Peek 已提交
671 672 673
          if @scope[:scope_level] == :resources
            raise ArgumentError, "can't define route directly in resources scope"
          end
J
Joshua Peek 已提交
674

J
Joshua Peek 已提交
675
          super
J
Joshua Peek 已提交
676 677
        end

678
        protected
679
          def parent_resource #:nodoc:
680 681 682
            @scope[:scope_level_resource]
          end

J
Joshua Peek 已提交
683
        private
684
          def action_path(name, path_names = nil)
685
            path_names ||= @scope[:path_names]
686 687 688
            path_names[name.to_sym] || name.to_s
          end

689
          def apply_common_behavior_for(method, resources, options, &block)
690 691 692 693 694 695
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

            if path_names = options.delete(:path_names)
696
              scope(:path_names => path_names) do
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
                send(method, resources.pop, options, &block)
              end
              return true
            end

            if @scope[:scope_level] == :resources
              nested do
                send(method, resources.pop, options, &block)
              end
              return true
            end

            false
          end

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
          def with_exclusive_name_prefix(prefix)
            begin
              old_name_prefix = @scope[:name_prefix]

              if !old_name_prefix.blank?
                @scope[:name_prefix] = "#{prefix}_#{@scope[:name_prefix]}"
              else
                @scope[:name_prefix] = prefix.to_s
              end

              yield
            ensure
              @scope[:name_prefix] = old_name_prefix
            end
          end

728
          def with_scope_level(kind, resource = parent_resource)
J
Joshua Peek 已提交
729
            old, @scope[:scope_level] = @scope[:scope_level], kind
730
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
J
Joshua Peek 已提交
731 732 733
            yield
          ensure
            @scope[:scope_level] = old
734
            @scope[:scope_level_resource] = old_resource
J
Joshua Peek 已提交
735 736
          end
      end
J
Joshua Peek 已提交
737

738 739 740 741
      include Base
      include HttpHelpers
      include Scoping
      include Resources
J
Joshua Peek 已提交
742 743
    end
  end
J
Joshua Peek 已提交
744
end