mapper.rb 21.3 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
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
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 183 184 185
      module Base
        def initialize(set)
          @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

        def default_url_options=(options)
          @set.default_url_options = options
        end
        alias_method :default_url_options, :default_url_options=
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
      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

220 221 222
        def redirect(*args, &block)
          options = args.last.is_a?(Hash) ? args.pop : {}

223 224 225
          path      = args.shift || block
          path_proc = path.is_a?(Proc) ? path : proc { |params| path % params }
          status    = options[:status] || 301
226
          body      = 'Moved Permanently'
227 228

          lambda do |env|
229
            req = Request.new(env)
230
            uri = URI.parse(path_proc.call(req.symbolized_path_parameters))
231 232
            uri.scheme ||= req.scheme
            uri.host   ||= req.host
233
            uri.port   ||= req.port unless req.port == 80
234 235 236 237 238 239 240

            headers = {
              'Location' => uri.to_s,
              'Content-Type' => 'text/html',
              'Content-Length' => body.length.to_s
            }
            [ status, headers, [body] ]
241
          end
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
        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
        def initialize(*args)
          @scope = {}
          super
        end

        def scope(*args)
          options = args.extract_options!
262
          options = options.dup
263 264 265 266 267 268 269 270

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

271
          recover = {}
272

273 274 275
          options[:constraints] ||= {}
          unless options[:constraints].is_a?(Hash)
            block, options[:constraints] = options[:constraints], {}
276
          end
277

278 279 280 281 282
          scope_options.each do |option|
            if value = options.delete(option)
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
283 284
          end

285 286
          recover[:block] = @scope[:blocks]
          @scope[:blocks] = merge_blocks_scope(@scope[:blocks], block)
287

288 289
          recover[:options] = @scope[:options]
          @scope[:options]  = merge_options_scope(@scope[:options], options)
290 291 292 293

          yield
          self
        ensure
294 295 296 297 298 299
          scope_options.each do |option|
            @scope[option] = recover[option] if recover.has_key?(option)
          end

          @scope[:options] = recover[:options]
          @scope[:blocks]  = recover[:block]
300 301 302 303 304 305 306
        end

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

        def namespace(path)
307
          scope(path.to_s, :name_prefix => path.to_s, :controller_namespace => path.to_s) { yield }
308 309 310 311 312 313
        end

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

314 315 316 317
        def defaults(defaults = {})
          scope(:defaults => defaults) { yield }
        end

318 319 320 321 322
        def match(*args)
          options = args.extract_options!

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

323 324
          if @scope[:name_prefix] && !options[:as].blank?
            options[:as] = "#{@scope[:name_prefix]}_#{options[:as]}"
325
          elsif @scope[:name_prefix] && options[:as] == ""
326
            options[:as] = @scope[:name_prefix].to_s
327 328 329 330 331
          end

          args.push(options)
          super(*args)
        end
332 333 334 335 336 337 338

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

          def merge_path_scope(parent, child)
339
            Mapper.normalize_path("#{parent}/#{child}")
340 341 342 343 344 345
          end

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

346
          def merge_controller_namespace_scope(parent, child)
347 348 349 350
            parent ? "#{parent}/#{child}" : child
          end

          def merge_controller_scope(parent, child)
351
            @scope[:controller_namespace] ? "#{@scope[:controller_namespace]}/#{child}" : child
352 353 354 355 356 357 358 359 360 361
          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

362 363 364 365
          def merge_defaults_scope(parent, child)
            merge_options_scope(parent, child)
          end

366 367 368 369 370 371 372
          def merge_blocks_scope(parent, child)
            (parent || []) + [child]
          end

          def merge_options_scope(parent, child)
            (parent || {}).merge(child)
          end
373 374
      end

J
Joshua Peek 已提交
375
      module Resources
376
        CRUD_ACTIONS = [:index, :show, :create, :update, :destroy]
377

378
        class Resource #:nodoc:
379 380 381 382 383
          def self.default_actions
            [:index, :create, :new, :show, :update, :destroy, :edit]
          end

          attr_reader :plural, :singular, :options
384 385

          def initialize(entities, options = {})
386
            @name = entities.to_s
387
            @options = options
388

389 390
            @plural   = @name.pluralize
            @singular = @name.singularize
391 392
          end

393 394 395 396 397 398
          def default_actions
            self.class.default_actions
          end

          def actions
            if only = options[:only]
399
              Array(only).map(&:to_sym)
400
            elsif except = options[:except]
401
              default_actions - Array(except).map(&:to_sym)
402 403 404 405 406
            else
              default_actions
            end
          end

407 408 409 410 411 412 413 414 415
          def action_type(action)
            case action
            when :index, :create
              :collection
            when :show, :update, :destroy
              :member
            end
          end

416
          def name
417
            options[:as] || @name
418 419 420
          end

          def controller
421
            options[:controller] || plural
422 423 424
          end

          def member_name
425
            singular
426 427 428
          end

          def collection_name
429 430 431 432 433
            uncountable? ? "#{plural}_index" : plural
          end
          
          def uncountable?
            singular == plural
434
          end
435

436 437 438 439 440 441 442 443 444
          def name_for_action(action)
            case action_type(action)
            when :collection
              collection_name
            when :member
              member_name
            end
          end

445 446 447
          def id_segment
            ":#{singular}_id"
          end
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

          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
474 475 476
        end

        class SingletonResource < Resource #:nodoc:
477 478 479 480
          def self.default_actions
            [:show, :create, :update, :destroy, :new, :edit]
          end

481
          def initialize(entity, options = {})
482
            super
483 484
          end

485 486 487 488 489 490 491
          def action_type(action)
            case action
            when :show, :create, :update, :destroy
              :member
            end
          end

492 493
          def member_name
            name
494 495 496
          end
        end

497 498 499 500 501
        def initialize(*args)
          super
          @scope[:resources_path_names] = @set.resources_path_names
        end

J
Joshua Peek 已提交
502
        def resource(*resources, &block)
J
Joshua Peek 已提交
503
          options = resources.extract_options!
J
Joshua Peek 已提交
504

505
          if apply_common_behavior_for(:resource, resources, options, &block)
506 507 508
            return self
          end

509
          resource = SingletonResource.new(resources.pop, options)
510

511
          scope(:path => resource.name.to_s, :controller => resource.controller) do
512
            with_scope_level(:resource, resource) do
513

514
              scope(:name_prefix => resource.name.to_s, :as => "") do
515 516
                yield if block_given?
              end
517

518 519 520 521 522 523 524 525
              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
526 527 528
            end
          end

J
Joshua Peek 已提交
529
          self
530 531
        end

J
Joshua Peek 已提交
532
        def resources(*resources, &block)
J
Joshua Peek 已提交
533
          options = resources.extract_options!
534

535
          if apply_common_behavior_for(:resources, resources, options, &block)
536 537 538
            return self
          end

539
          resource = Resource.new(resources.pop, options)
540

541
          scope(:path => resource.name.to_s, :controller => resource.controller) do
542 543
            with_scope_level(:resources, resource) do
              yield if block_given?
J
Joshua Peek 已提交
544

545
              with_scope_level(:collection) do
546 547 548 549 550
                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
551
              end
552

553
              with_scope_level(:member) do
554
                scope(':id') do
555 556 557 558 559 560
                  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 已提交
561
                end
562 563 564 565
              end
            end
          end

J
Joshua Peek 已提交
566
          self
567 568
        end

J
Joshua Peek 已提交
569 570 571
        def collection
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use collection outside resources scope"
572 573
          end

J
Joshua Peek 已提交
574
          with_scope_level(:collection) do
575
            scope(:name_prefix => parent_resource.collection_name, :as => "") do
576 577
              yield
            end
J
Joshua Peek 已提交
578
          end
579
        end
J
Joshua Peek 已提交
580

J
Joshua Peek 已提交
581 582 583 584
        def member
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use member outside resources scope"
          end
J
Joshua Peek 已提交
585

J
Joshua Peek 已提交
586
          with_scope_level(:member) do
587
            scope(':id', :name_prefix => parent_resource.member_name, :as => "") do
J
Joshua Peek 已提交
588 589 590
              yield
            end
          end
J
Joshua Peek 已提交
591 592
        end

593 594 595 596 597 598
        def nested
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use nested outside resources scope"
          end

          with_scope_level(:nested) do
599
            scope(parent_resource.id_segment, parent_resource.nested_options) do
600 601 602 603 604
              yield
            end
          end
        end

605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
        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

J
Joshua Peek 已提交
620
        def match(*args)
J
Joshua Peek 已提交
621
          options = args.extract_options!
622

623 624
          options[:anchor] = true unless options.key?(:anchor)

625 626 627 628 629
          if args.length > 1
            args.each { |path| match(path, options) }
            return self
          end

630 631
          resources_path_names = options.delete(:path_names)

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

J
Joshua Peek 已提交
652
          args.push(options)
J
Joshua Peek 已提交
653

J
Joshua Peek 已提交
654 655 656 657 658 659
          case options.delete(:on)
          when :collection
            return collection { match(*args) }
          when :member
            return member { match(*args) }
          end
J
Joshua Peek 已提交
660

J
Joshua Peek 已提交
661 662 663
          if @scope[:scope_level] == :resources
            raise ArgumentError, "can't define route directly in resources scope"
          end
J
Joshua Peek 已提交
664

J
Joshua Peek 已提交
665
          super
J
Joshua Peek 已提交
666 667
        end

668 669 670 671 672
        protected
          def parent_resource
            @scope[:scope_level_resource]
          end

J
Joshua Peek 已提交
673
        private
674 675 676 677 678
          def action_path(name, path_names = nil)
            path_names ||= @scope[:resources_path_names]
            path_names[name.to_sym] || name.to_s
          end

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

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
          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

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

728 729 730 731
      include Base
      include HttpHelpers
      include Scoping
      include Resources
J
Joshua Peek 已提交
732 733
    end
  end
J
Joshua Peek 已提交
734
end