mapper.rb 22.2 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 61 62 63 64 65
            if @scope[:module] && options[:to]
              if options[:to].to_s.include?("#")
                options[:to] = "#{@scope[:module]}/#{options[:to]}"
              elsif @scope[:controller].nil?
                options[:to] = "#{@scope[:module]}##{options[:to]}"
              end
            end

66
            path = normalize_path(path)
67
            path_without_format = path.sub(/\(\.:format\)$/, '')
68

69 70 71
            if using_match_shorthand?(path_without_format, options)
              options[:to] ||= path_without_format[1..-1].sub(%r{/([^/]*)$}, '#\1')
              options[:as] ||= path_without_format[1..-1].gsub("/", "_")
72 73 74
            end

            [ path, options ]
75
          end
76

77 78 79 80
          # match "account" => "account#index"
          def using_to_shorthand?(args, options)
            args.empty? && options.present?
          end
81

82
          # match "account/overview"
83
          def using_match_shorthand?(path, options)
84
            path && options.except(:via, :anchor, :to, :as).empty? && path =~ %r{^/[\w\/]+$}
85
          end
86

87
          def normalize_path(path)
88 89
            raise ArgumentError, "path is required" if @scope[:path].blank? && path.blank?
            Mapper.normalize_path("#{@scope[:path]}/#{path}")
90
          end
91

92 93 94
          def app
            Constraints.new(
              to.respond_to?(:call) ? to : Routing::RouteSet::Dispatcher.new(:defaults => defaults),
95 96
              blocks,
              @set.request_class
97
            )
98 99
          end

100 101 102
          def conditions
            { :path_info => @path }.merge(constraints).merge(request_method_condition)
          end
J
Joshua Peek 已提交
103

104
          def requirements
105
            @requirements ||= (@options[:constraints] || {}).tap do |requirements|
106 107 108 109
              requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints]
              @options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) }
            end
          end
110

111
          def defaults
112 113 114 115 116 117 118 119 120
            @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)
121 122 123 124 125 126 127
              { }
            else
              defaults = case to
              when String
                controller, action = to.split('#')
                { :controller => controller, :action => action }
              when Symbol
128
                { :action => to.to_s }
129
              else
130
                {}
131
              end
J
Joshua Peek 已提交
132

133 134 135 136
              defaults[:controller] ||= default_controller

              defaults.delete(:controller) if defaults[:controller].blank?
              defaults.delete(:action)     if defaults[:action].blank?
137

138 139 140
              if defaults[:controller].blank? && segment_keys.exclude?("controller")
                raise ArgumentError, "missing :controller"
              end
J
Joshua Peek 已提交
141

142 143 144
              if defaults[:action].blank? && segment_keys.exclude?("action")
                raise ArgumentError, "missing :action"
              end
J
Joshua Peek 已提交
145

146 147 148
              defaults
            end
          end
149

150 151 152 153 154 155
          def blocks
            if @options[:constraints].present? && !@options[:constraints].is_a?(Hash)
              block = @options[:constraints]
            else
              block = nil
            end
J
Joshua Peek 已提交
156 157

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

160 161 162
          def constraints
            @constraints ||= requirements.reject { |k, v| segment_keys.include?(k.to_s) || k == :controller }
          end
163

164 165 166 167 168 169
          def request_method_condition
            if via = @options[:via]
              via = Array(via).map { |m| m.to_s.upcase }
              { :request_method => Regexp.union(*via) }
            else
              { }
170
            end
171
          end
J
Joshua Peek 已提交
172

173 174
          def segment_keys
            @segment_keys ||= Rack::Mount::RegexpWithNamedGroups.new(
175 176
              Rack::Mount::Strexp.compile(@path, requirements, SEPARATORS)
            ).names
177
          end
178

179 180 181
          def to
            @options[:to]
          end
J
Joshua Peek 已提交
182

183
          def default_controller
184 185 186 187 188
            if @options[:controller]
              @options[:controller].to_s
            elsif @scope[:controller]
              @scope[:controller].to_s
            end
189
          end
190
      end
191

192
      # Invokes Rack::Mount::Utils.normalize path and ensure that
193 194
      # (:locale) becomes (/:locale) instead of /(:locale). Except
      # for root cases, where the latter is the correct one.
195 196
      def self.normalize_path(path)
        path = Rack::Mount::Utils.normalize_path(path)
197
        path.sub!(%r{/(\(+)/?:}, '\1/:') unless path =~ %r{^/\(+:.*\)$}
198 199 200
        path
      end

201
      module Base
202
        def initialize(set) #:nodoc:
203 204
          @set = set
        end
205

206 207 208
        def root(options = {})
          match '/', options.reverse_merge(:as => :root)
        end
209

210
        def match(*args)
211 212
          mapping = Mapping.new(@set, @scope, args).to_route
          @set.add_route(*mapping)
213 214
          self
        end
215

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        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

231 232 233 234
        def default_url_options=(options)
          @set.default_url_options = options
        end
        alias_method :default_url_options, :default_url_options=
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
      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

254 255 256
        def redirect(*args, &block)
          options = args.last.is_a?(Hash) ? args.pop : {}

257 258 259
          path      = args.shift || block
          path_proc = path.is_a?(Proc) ? path : proc { |params| path % params }
          status    = options[:status] || 301
260
          body      = 'Moved Permanently'
261 262

          lambda do |env|
263
            req = Request.new(env)
264 265 266 267 268

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

            uri = URI.parse(path_proc.call(*params))
269 270
            uri.scheme ||= req.scheme
            uri.host   ||= req.host
271
            uri.port   ||= req.port unless req.port == 80
272 273 274 275 276 277 278

            headers = {
              'Location' => uri.to_s,
              'Content-Type' => 'text/html',
              'Content-Length' => body.length.to_s
            }
            [ status, headers, [body] ]
279
          end
280 281 282 283 284 285 286 287 288 289 290 291 292
        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
293
        def initialize(*args) #:nodoc:
294 295 296 297 298 299
          @scope = {}
          super
        end

        def scope(*args)
          options = args.extract_options!
300
          options = options.dup
301 302 303 304 305 306 307 308

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

309
          recover = {}
310

311 312 313
          options[:constraints] ||= {}
          unless options[:constraints].is_a?(Hash)
            block, options[:constraints] = options[:constraints], {}
314
          end
315

316 317 318 319 320
          scope_options.each do |option|
            if value = options.delete(option)
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
321 322
          end

323 324
          recover[:block] = @scope[:blocks]
          @scope[:blocks] = merge_blocks_scope(@scope[:blocks], block)
325

326 327
          recover[:options] = @scope[:options]
          @scope[:options]  = merge_options_scope(@scope[:options], options)
328 329 330 331

          yield
          self
        ensure
332 333 334 335 336 337
          scope_options.each do |option|
            @scope[option] = recover[option] if recover.has_key?(option)
          end

          @scope[:options] = recover[:options]
          @scope[:blocks]  = recover[:block]
338 339 340 341 342 343
        end

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

344 345 346
        def namespace(path)
          path = path.to_s
          scope(:path => path, :name_prefix => path, :module => path) { yield }
347 348 349 350 351 352
        end

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

353 354 355 356
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

357 358 359 360 361
        def match(*args)
          options = args.extract_options!

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

362 363
          if @scope[:name_prefix] && !options[:as].blank?
            options[:as] = "#{@scope[:name_prefix]}_#{options[:as]}"
364
          elsif @scope[:name_prefix] && options[:as] == ""
365
            options[:as] = @scope[:name_prefix].to_s
366 367 368 369 370
          end

          args.push(options)
          super(*args)
        end
371 372 373 374 375 376 377

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

          def merge_path_scope(parent, child)
378
            Mapper.normalize_path("#{parent}/#{child}")
379 380 381 382 383 384
          end

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

385
          def merge_module_scope(parent, child)
386 387 388 389
            parent ? "#{parent}/#{child}" : child
          end

          def merge_controller_scope(parent, child)
390
            @scope[:module] ? "#{@scope[:module]}/#{child}" : child
391 392
          end

393
          def merge_path_names_scope(parent, child)
394 395 396 397 398 399 400
            merge_options_scope(parent, child)
          end

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

401 402 403 404
          def merge_defaults_scope(parent, child)
            merge_options_scope(parent, child)
          end

405 406 407 408 409 410 411
          def merge_blocks_scope(parent, child)
            (parent || []) + [child]
          end

          def merge_options_scope(parent, child)
            (parent || {}).merge(child)
          end
412 413
      end

J
Joshua Peek 已提交
414
      module Resources
415
        CRUD_ACTIONS = [:index, :show, :create, :update, :destroy] #:nodoc:
416

417
        class Resource #:nodoc:
418 419 420 421
          def self.default_actions
            [:index, :create, :new, :show, :update, :destroy, :edit]
          end

422
          attr_reader :controller, :path, :options
423 424

          def initialize(entities, options = {})
425 426 427 428
            @name       = entities.to_s
            @path       = options.delete(:path) || @name
            @controller = options.delete(:controller) || @name.to_s.pluralize
            @options    = options
429 430
          end

431 432 433 434 435 436
          def default_actions
            self.class.default_actions
          end

          def actions
            if only = options[:only]
437
              Array(only).map(&:to_sym)
438
            elsif except = options[:except]
439
              default_actions - Array(except).map(&:to_sym)
440 441 442 443 444
            else
              default_actions
            end
          end

445 446 447 448 449 450 451 452 453
          def action_type(action)
            case action
            when :index, :create
              :collection
            when :show, :update, :destroy
              :member
            end
          end

454
          def name
455
            options[:as] || @name
456 457
          end

458 459 460 461 462 463
          def plural
            name.to_s.pluralize
          end

          def singular
            name.to_s.singularize
464 465 466
          end

          def member_name
467
            singular
468 469
          end

470
          # Checks for uncountable plurals, and appends "_index" if they're.
471
          def collection_name
472 473
            uncountable? ? "#{plural}_index" : plural
          end
474

475 476
          def uncountable?
            singular == plural
477
          end
478

479 480 481 482 483 484 485 486 487
          def name_for_action(action)
            case action_type(action)
            when :collection
              collection_name
            when :member
              member_name
            end
          end

488 489 490
          def id_segment
            ":#{singular}_id"
          end
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516

          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
517 518 519
        end

        class SingletonResource < Resource #:nodoc:
520 521 522 523
          def self.default_actions
            [:show, :create, :update, :destroy, :new, :edit]
          end

524
          def initialize(entity, options = {})
525
            super
526 527
          end

528 529 530 531 532 533 534
          def action_type(action)
            case action
            when :show, :create, :update, :destroy
              :member
            end
          end

535 536
          def member_name
            name
537 538 539
          end
        end

540
        def initialize(*args) #:nodoc:
541
          super
542
          @scope[:path_names] = @set.resources_path_names
543 544
        end

J
Joshua Peek 已提交
545
        def resource(*resources, &block)
J
Joshua Peek 已提交
546
          options = resources.extract_options!
J
Joshua Peek 已提交
547

548
          if apply_common_behavior_for(:resource, resources, options, &block)
549 550 551
            return self
          end

552
          resource = SingletonResource.new(resources.pop, options)
553

554
          scope(:path => resource.path, :controller => resource.controller) do
555
            with_scope_level(:resource, resource) do
556

557
              scope(:name_prefix => resource.name.to_s, :as => "") do
558 559
                yield if block_given?
              end
560

561 562 563 564 565 566 567 568
              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
569 570 571
            end
          end

J
Joshua Peek 已提交
572
          self
573 574
        end

J
Joshua Peek 已提交
575
        def resources(*resources, &block)
J
Joshua Peek 已提交
576
          options = resources.extract_options!
577

578
          if apply_common_behavior_for(:resources, resources, options, &block)
579 580 581
            return self
          end

582
          resource = Resource.new(resources.pop, options)
583

584
          scope(:path => resource.path, :controller => resource.controller) do
585 586
            with_scope_level(:resources, resource) do
              yield if block_given?
J
Joshua Peek 已提交
587

588
              with_scope_level(:collection) do
589 590 591 592 593
                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
594
              end
595

596
              with_scope_level(:member) do
597
                scope(':id') do
598 599 600 601 602 603
                  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 已提交
604
                end
605 606 607 608
              end
            end
          end

J
Joshua Peek 已提交
609
          self
610 611
        end

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

J
Joshua Peek 已提交
617
          with_scope_level(:collection) do
618
            scope(:name_prefix => parent_resource.collection_name, :as => "") do
619 620
              yield
            end
J
Joshua Peek 已提交
621
          end
622
        end
J
Joshua Peek 已提交
623

J
Joshua Peek 已提交
624 625 626 627
        def member
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use member outside resources scope"
          end
J
Joshua Peek 已提交
628

J
Joshua Peek 已提交
629
          with_scope_level(:member) do
630
            scope(':id', :name_prefix => parent_resource.member_name, :as => "") do
J
Joshua Peek 已提交
631 632 633
              yield
            end
          end
J
Joshua Peek 已提交
634 635
        end

636 637 638 639 640 641
        def nested
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use nested outside resources scope"
          end

          with_scope_level(:nested) do
642
            scope(parent_resource.id_segment, parent_resource.nested_options) do
643 644 645 646 647
              yield
            end
          end
        end

J
Joshua Peek 已提交
648
        def match(*args)
J
Joshua Peek 已提交
649
          options = args.extract_options!
650

651 652
          options[:anchor] = true unless options.key?(:anchor)

653 654 655 656 657
          if args.length > 1
            args.each { |path| match(path, options) }
            return self
          end

658
          path_names = options.delete(:path_names)
659

660
          if args.first.is_a?(Symbol)
661 662
            action = args.first
            if CRUD_ACTIONS.include?(action)
663 664 665
              begin
                old_path = @scope[:path]
                @scope[:path] = "#{@scope[:path]}(.:format)"
666 667 668 669
                return match(options.reverse_merge(
                  :to => action,
                  :as => parent_resource.name_for_action(action)
                ))
670 671 672
              ensure
                @scope[:path] = old_path
              end
673 674
            else
              with_exclusive_name_prefix(action) do
675
                return match("#{action_path(action, path_names)}(.:format)", options.reverse_merge(:to => action))
676
              end
677 678 679
            end
          end

J
Joshua Peek 已提交
680
          args.push(options)
J
Joshua Peek 已提交
681

J
Joshua Peek 已提交
682 683 684 685 686 687
          case options.delete(:on)
          when :collection
            return collection { match(*args) }
          when :member
            return member { match(*args) }
          end
J
Joshua Peek 已提交
688

J
Joshua Peek 已提交
689 690 691
          if @scope[:scope_level] == :resources
            raise ArgumentError, "can't define route directly in resources scope"
          end
J
Joshua Peek 已提交
692

J
Joshua Peek 已提交
693
          super
J
Joshua Peek 已提交
694 695
        end

696
        protected
697
          def parent_resource #:nodoc:
698 699 700
            @scope[:scope_level_resource]
          end

J
Joshua Peek 已提交
701
        private
702
          def action_path(name, path_names = nil)
703
            path_names ||= @scope[:path_names]
704 705 706
            path_names[name.to_sym] || name.to_s
          end

707
          def apply_common_behavior_for(method, resources, options, &block)
708 709 710 711 712 713
            if resources.length > 1
              resources.each { |r| send(method, r, options, &block) }
              return true
            end

            if path_names = options.delete(:path_names)
714
              scope(:path_names => path_names) do
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
                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

730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
          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

746
          def with_scope_level(kind, resource = parent_resource)
J
Joshua Peek 已提交
747
            old, @scope[:scope_level] = @scope[:scope_level], kind
748
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
J
Joshua Peek 已提交
749 750 751
            yield
          ensure
            @scope[:scope_level] = old
752
            @scope[:scope_level_resource] = old_resource
J
Joshua Peek 已提交
753 754
          end
      end
J
Joshua Peek 已提交
755

756 757 758 759
      include Base
      include HttpHelpers
      include Scoping
      include Resources
J
Joshua Peek 已提交
760 761
    end
  end
J
Joshua Peek 已提交
762
end