mapper.rb 21.5 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 = [])
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
          if constraints.any?
            super(app, constraints)
          else
            app
          end
        end

        def initialize(app, constraints = [])
          @app, @constraints = app, constraints
        end

        def call(env)
          req = Rack::Request.new(env)

          @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 86 87
          def app
            Constraints.new(
              to.respond_to?(:call) ? to : Routing::RouteSet::Dispatcher.new(:defaults => defaults),
              blocks
            )
88 89
          end

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

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

101
          def defaults
102 103 104 105 106 107 108 109 110
            @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)
111 112 113 114 115 116 117
              { }
            else
              defaults = case to
              when String
                controller, action = to.split('#')
                { :controller => controller, :action => action }
              when Symbol
118
                { :action => to.to_s }.merge(default_controller ? { :controller => default_controller } : {})
119
              else
120
                default_controller ? { :controller => default_controller } : {}
121
              end
J
Joshua Peek 已提交
122

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

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

131 132 133
              defaults
            end
          end
134

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

          lambda do |env|
244
            req = Request.new(env)
245
            uri = URI.parse(path_proc.call(req.symbolized_path_parameters))
246 247
            uri.scheme ||= req.scheme
            uri.host   ||= req.host
248
            uri.port   ||= req.port unless req.port == 80
249 250 251 252 253 254 255

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

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

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

286
          recover = {}
287

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

          def merge_controller_scope(parent, child)
366
            @scope[:controller_namespace] ? "#{@scope[:controller_namespace]}/#{child}" : child
367 368 369 370 371 372 373 374 375 376
          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

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

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

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

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

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

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

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

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

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

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

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

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

          def singular
            name.to_s.singularize
440 441 442
          end

          def member_name
443
            singular
444 445
          end

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

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

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

464 465 466
          def id_segment
            ":#{singular}_id"
          end
467 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

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

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

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

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

511 512
          def member_name
            name
513 514 515
          end
        end

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

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

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

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

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

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

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

J
Joshua Peek 已提交
548
          self
549 550
        end

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

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

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

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

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

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

J
Joshua Peek 已提交
585
          self
586 587
        end

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

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

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

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

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

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

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

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

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

634 635
          resources_path_names = options.delete(:path_names)

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

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

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

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

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

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

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

683
          def apply_common_behavior_for(method, resources, options, &block)
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
            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

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

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

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