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
            uri = URI.parse(path_proc.call(req.symbolized_path_parameters))
247 248
            uri.scheme ||= req.scheme
            uri.host   ||= req.host
249
            uri.port   ||= req.port unless req.port == 80
250 251 252 253 254 255 256

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

        def scope(*args)
          options = args.extract_options!
278
          options = options.dup
279 280 281 282 283 284 285 286

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

287
          recover = {}
288

289 290 291
          options[:constraints] ||= {}
          unless options[:constraints].is_a?(Hash)
            block, options[:constraints] = options[:constraints], {}
292
          end
293

294 295 296 297 298
          scope_options.each do |option|
            if value = options.delete(option)
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
299 300
          end

301 302
          recover[:block] = @scope[:blocks]
          @scope[:blocks] = merge_blocks_scope(@scope[:blocks], block)
303

304 305
          recover[:options] = @scope[:options]
          @scope[:options]  = merge_options_scope(@scope[:options], options)
306 307 308 309

          yield
          self
        ensure
310 311 312 313 314 315
          scope_options.each do |option|
            @scope[option] = recover[option] if recover.has_key?(option)
          end

          @scope[:options] = recover[:options]
          @scope[:blocks]  = recover[:block]
316 317 318 319 320 321 322
        end

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

        def namespace(path)
323
          scope(path.to_s, :name_prefix => path.to_s, :controller_namespace => path.to_s) { yield }
324 325 326 327 328 329
        end

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

330 331 332 333
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

334 335 336 337 338
        def match(*args)
          options = args.extract_options!

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

339 340
          if @scope[:name_prefix] && !options[:as].blank?
            options[:as] = "#{@scope[:name_prefix]}_#{options[:as]}"
341
          elsif @scope[:name_prefix] && options[:as] == ""
342
            options[:as] = @scope[:name_prefix].to_s
343 344 345 346 347
          end

          args.push(options)
          super(*args)
        end
348 349 350 351 352 353 354

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

          def merge_path_scope(parent, child)
355
            Mapper.normalize_path("#{parent}/#{child}")
356 357 358 359 360 361
          end

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

362
          def merge_controller_namespace_scope(parent, child)
363 364 365 366
            parent ? "#{parent}/#{child}" : child
          end

          def merge_controller_scope(parent, child)
367
            @scope[:controller_namespace] ? "#{@scope[:controller_namespace]}/#{child}" : child
368 369 370 371 372 373 374 375 376 377
          end

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

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

378 379 380 381
          def merge_defaults_scope(parent, child)
            merge_options_scope(parent, child)
          end

382 383 384 385 386 387 388
          def merge_blocks_scope(parent, child)
            (parent || []) + [child]
          end

          def merge_options_scope(parent, child)
            (parent || {}).merge(child)
          end
389 390
      end

J
Joshua Peek 已提交
391
      module Resources
392
        CRUD_ACTIONS = [:index, :show, :create, :update, :destroy] #:nodoc:
393

394
        class Resource #:nodoc:
395 396 397 398
          def self.default_actions
            [:index, :create, :new, :show, :update, :destroy, :edit]
          end

399
          attr_reader :controller, :path, :options
400 401

          def initialize(entities, options = {})
402 403 404 405
            @name       = entities.to_s
            @path       = options.delete(:path) || @name
            @controller = options.delete(:controller) || @name.to_s.pluralize
            @options    = options
406 407
          end

408 409 410 411 412 413
          def default_actions
            self.class.default_actions
          end

          def actions
            if only = options[:only]
414
              Array(only).map(&:to_sym)
415
            elsif except = options[:except]
416
              default_actions - Array(except).map(&:to_sym)
417 418 419 420 421
            else
              default_actions
            end
          end

422 423 424 425 426 427 428 429 430
          def action_type(action)
            case action
            when :index, :create
              :collection
            when :show, :update, :destroy
              :member
            end
          end

431
          def name
432
            options[:as] || @name
433 434
          end

435 436 437 438 439 440
          def plural
            name.to_s.pluralize
          end

          def singular
            name.to_s.singularize
441 442 443
          end

          def member_name
444
            singular
445 446
          end

447
          # Checks for uncountable plurals, and appends "_index" if they're.
448
          def collection_name
449 450
            uncountable? ? "#{plural}_index" : plural
          end
451

452 453
          def uncountable?
            singular == plural
454
          end
455

456 457 458 459 460 461 462 463 464
          def name_for_action(action)
            case action_type(action)
            when :collection
              collection_name
            when :member
              member_name
            end
          end

465 466 467
          def id_segment
            ":#{singular}_id"
          end
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493

          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
494 495 496
        end

        class SingletonResource < Resource #:nodoc:
497 498 499 500
          def self.default_actions
            [:show, :create, :update, :destroy, :new, :edit]
          end

501
          def initialize(entity, options = {})
502
            super
503 504
          end

505 506 507 508 509 510 511
          def action_type(action)
            case action
            when :show, :create, :update, :destroy
              :member
            end
          end

512 513
          def member_name
            name
514 515 516
          end
        end

517
        def initialize(*args) #:nodoc:
518 519 520 521
          super
          @scope[:resources_path_names] = @set.resources_path_names
        end

J
Joshua Peek 已提交
522
        def resource(*resources, &block)
J
Joshua Peek 已提交
523
          options = resources.extract_options!
J
Joshua Peek 已提交
524

525
          if apply_common_behavior_for(:resource, resources, options, &block)
526 527 528
            return self
          end

529
          resource = SingletonResource.new(resources.pop, options)
530

531
          scope(:path => resource.path, :controller => resource.controller) do
532
            with_scope_level(:resource, resource) do
533

534
              scope(:name_prefix => resource.name.to_s, :as => "") do
535 536
                yield if block_given?
              end
537

538 539 540 541 542 543 544 545
              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
546 547 548
            end
          end

J
Joshua Peek 已提交
549
          self
550 551
        end

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

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

559
          resource = Resource.new(resources.pop, options)
560

561
          scope(:path => resource.path, :controller => resource.controller) do
562 563
            with_scope_level(:resources, resource) do
              yield if block_given?
J
Joshua Peek 已提交
564

565
              with_scope_level(:collection) do
566 567 568 569 570
                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
571
              end
572

573
              with_scope_level(:member) do
574
                scope(':id') do
575 576 577 578 579 580
                  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 已提交
581
                end
582 583 584 585
              end
            end
          end

J
Joshua Peek 已提交
586
          self
587 588
        end

J
Joshua Peek 已提交
589 590 591
        def collection
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use collection outside resources scope"
592 593
          end

J
Joshua Peek 已提交
594
          with_scope_level(:collection) do
595
            scope(:name_prefix => parent_resource.collection_name, :as => "") do
596 597
              yield
            end
J
Joshua Peek 已提交
598
          end
599
        end
J
Joshua Peek 已提交
600

J
Joshua Peek 已提交
601 602 603 604
        def member
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use member outside resources scope"
          end
J
Joshua Peek 已提交
605

J
Joshua Peek 已提交
606
          with_scope_level(:member) do
607
            scope(':id', :name_prefix => parent_resource.member_name, :as => "") do
J
Joshua Peek 已提交
608 609 610
              yield
            end
          end
J
Joshua Peek 已提交
611 612
        end

613 614 615 616 617 618
        def nested
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use nested outside resources scope"
          end

          with_scope_level(:nested) do
619
            scope(parent_resource.id_segment, parent_resource.nested_options) do
620 621 622 623 624
              yield
            end
          end
        end

J
Joshua Peek 已提交
625
        def match(*args)
J
Joshua Peek 已提交
626
          options = args.extract_options!
627

628 629
          options[:anchor] = true unless options.key?(:anchor)

630 631 632 633 634
          if args.length > 1
            args.each { |path| match(path, options) }
            return self
          end

635 636
          resources_path_names = options.delete(:path_names)

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

J
Joshua Peek 已提交
657
          args.push(options)
J
Joshua Peek 已提交
658

J
Joshua Peek 已提交
659 660 661 662 663 664
          case options.delete(:on)
          when :collection
            return collection { match(*args) }
          when :member
            return member { match(*args) }
          end
J
Joshua Peek 已提交
665

J
Joshua Peek 已提交
666 667 668
          if @scope[:scope_level] == :resources
            raise ArgumentError, "can't define route directly in resources scope"
          end
J
Joshua Peek 已提交
669

J
Joshua Peek 已提交
670
          super
J
Joshua Peek 已提交
671 672
        end

673
        protected
674
          def parent_resource #:nodoc:
675 676 677
            @scope[:scope_level_resource]
          end

J
Joshua Peek 已提交
678
        private
679 680 681 682 683
          def action_path(name, path_names = nil)
            path_names ||= @scope[:resources_path_names]
            path_names[name.to_sym] || name.to_s
          end

684
          def apply_common_behavior_for(method, resources, options, &block)
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

            if path_names = options.delete(:path_names)
              scope(:resources_path_names => path_names) do
                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

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
          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

723
          def with_scope_level(kind, resource = parent_resource)
J
Joshua Peek 已提交
724
            old, @scope[:scope_level] = @scope[:scope_level], kind
725
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
J
Joshua Peek 已提交
726 727 728
            yield
          ensure
            @scope[:scope_level] = old
729
            @scope[:scope_level_resource] = old_resource
J
Joshua Peek 已提交
730 731
          end
      end
J
Joshua Peek 已提交
732

733 734 735 736
      include Base
      include HttpHelpers
      include Scoping
      include Resources
J
Joshua Peek 已提交
737 738
    end
  end
J
Joshua Peek 已提交
739
end