mapper.rb 18.6 KB
Newer Older
J
Joshua Peek 已提交
1 2
module ActionDispatch
  module Routing
J
Joshua Peek 已提交
3
    class Mapper
4
      class Constraints
5
        def self.new(app, constraints = [])
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
          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 已提交
22
              return [ 404, {'X-Cascade' => 'pass'}, [] ]
23
            elsif constraint.respond_to?(:call) && !constraint.call(req)
J
Joshua Peek 已提交
24
              return [ 404, {'X-Cascade' => 'pass'}, [] ]
25 26 27 28 29 30 31
            end
          }

          @app.call(env)
        end
      end

32 33 34 35
      class Mapping
        def initialize(set, scope, args)
          @set, @scope    = set, scope
          @path, @options = extract_path_and_options(args)
36
        end
J
Joshua Peek 已提交
37

38 39
        def to_route
          [ app, conditions, requirements, defaults, @options[:as] ]
40
        end
J
Joshua Peek 已提交
41

42 43
        private
          def extract_path_and_options(args)
44
            options = args.extract_options!
45

46 47
            case
            when using_to_shorthand?(args, options)
48 49
              path, to = options.find { |name, value| name.is_a?(String) }
              options.merge!(:to => to).delete(path) if path
50 51 52
            when using_match_shorthand?(args, options)
              path = args.first
              options = { :to => path.gsub("/", "#"), :as => path.gsub("/", "_") }
53 54 55
            else
              path = args.first
            end
J
Joshua Peek 已提交
56

57
            [ normalize_path(path), options ]
58
          end
59

60 61 62 63
          # match "account" => "account#index"
          def using_to_shorthand?(args, options)
            args.empty? && options.present?
          end
64

65 66
          # match "account/overview"
          def using_match_shorthand?(args, options)
67
            args.present? && options.except(:via).empty? && !args.first.include?(':')
68
          end
69

70
          def normalize_path(path)
71
            path = "#{@scope[:path]}/#{path}"
72 73
            raise ArgumentError, "path is required" if path.empty?
            Mapper.normalize_path(path)
74
          end
75

76 77 78 79 80
          def app
            Constraints.new(
              to.respond_to?(:call) ? to : Routing::RouteSet::Dispatcher.new(:defaults => defaults),
              blocks
            )
81 82
          end

83 84 85
          def conditions
            { :path_info => @path }.merge(constraints).merge(request_method_condition)
          end
J
Joshua Peek 已提交
86

87 88 89 90 91 92 93
          def requirements
            @requirements ||= returning(@options[:constraints] || {}) do |requirements|
              requirements.reverse_merge!(@scope[:constraints]) if @scope[:constraints]
              @options.each { |k, v| requirements[k] = v if v.is_a?(Regexp) }
              requirements[:controller] ||= @set.controller_constraints
            end
          end
94

95 96 97 98 99 100 101 102 103
          def defaults
            @defaults ||= if to.respond_to?(:call)
              { }
            else
              defaults = case to
              when String
                controller, action = to.split('#')
                { :controller => controller, :action => action }
              when Symbol
104
                { :action => to.to_s }.merge(default_controller ? { :controller => default_controller } : {})
105
              else
106
                default_controller ? { :controller => default_controller } : {}
107
              end
J
Joshua Peek 已提交
108

109 110 111
              if defaults[:controller].blank? && segment_keys.exclude?("controller")
                raise ArgumentError, "missing :controller"
              end
J
Joshua Peek 已提交
112

113 114 115
              if defaults[:action].blank? && segment_keys.exclude?("action")
                raise ArgumentError, "missing :action"
              end
J
Joshua Peek 已提交
116

117 118 119
              defaults
            end
          end
120

121 122 123 124 125 126
          def blocks
            if @options[:constraints].present? && !@options[:constraints].is_a?(Hash)
              block = @options[:constraints]
            else
              block = nil
            end
J
Joshua Peek 已提交
127 128

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

131 132 133
          def constraints
            @constraints ||= requirements.reject { |k, v| segment_keys.include?(k.to_s) || k == :controller }
          end
134

135 136 137 138 139 140
          def request_method_condition
            if via = @options[:via]
              via = Array(via).map { |m| m.to_s.upcase }
              { :request_method => Regexp.union(*via) }
            else
              { }
141
            end
142
          end
J
Joshua Peek 已提交
143

144 145 146 147 148
          def segment_keys
            @segment_keys ||= Rack::Mount::RegexpWithNamedGroups.new(
                Rack::Mount::Strexp.compile(@path, requirements, SEPARATORS)
              ).names
          end
149

150 151 152
          def to
            @options[:to]
          end
J
Joshua Peek 已提交
153

154 155
          def default_controller
            @scope[:controller].to_s if @scope[:controller]
156
          end
157
      end
158

159
      # Invokes Rack::Mount::Utils.normalize path and ensure that
160 161
      # (:locale) becomes (/:locale) instead of /(:locale). Except
      # for root cases, where the latter is the correct one.
162 163
      def self.normalize_path(path)
        path = Rack::Mount::Utils.normalize_path(path)
164
        path.sub!(%r{/(\(+)/?:}, '\1/:') unless path =~ %r{^/\(+:.*\)$}
165 166 167
        path
      end

168 169 170 171
      module Base
        def initialize(set)
          @set = set
        end
172

173 174 175
        def root(options = {})
          match '/', options.reverse_merge(:as => :root)
        end
176

177 178 179 180
        def match(*args)
          @set.add_route(*Mapping.new(@set, @scope, args).to_route)
          self
        end
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
      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

200 201 202
        def redirect(*args, &block)
          options = args.last.is_a?(Hash) ? args.pop : {}

203 204 205
          path      = args.shift || block
          path_proc = path.is_a?(Proc) ? path : proc { |params| path % params }
          status    = options[:status] || 301
206
          body      = 'Moved Permanently'
207 208

          lambda do |env|
209 210
            req = Request.new(env)

211
            uri = URI.parse(path_proc.call(req.params.symbolize_keys))
212 213
            uri.scheme ||= req.scheme
            uri.host   ||= req.host
214
            uri.port   ||= req.port unless req.port == 80
215 216 217 218 219 220 221

            headers = {
              'Location' => uri.to_s,
              'Content-Type' => 'text/html',
              'Content-Length' => body.length.to_s
            }
            [ status, headers, [body] ]
222
          end
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        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!

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

251
          recover = {}
252

253 254 255
          options[:constraints] ||= {}
          unless options[:constraints].is_a?(Hash)
            block, options[:constraints] = options[:constraints], {}
256
          end
257

258 259 260 261 262
          scope_options.each do |option|
            if value = options.delete(option)
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
263 264
          end

265 266
          recover[:block] = @scope[:blocks]
          @scope[:blocks] = merge_blocks_scope(@scope[:blocks], block)
267

268 269
          recover[:options] = @scope[:options]
          @scope[:options]  = merge_options_scope(@scope[:options], options)
270 271 272 273

          yield
          self
        ensure
274 275 276 277 278 279
          scope_options.each do |option|
            @scope[option] = recover[option] if recover.has_key?(option)
          end

          @scope[:options] = recover[:options]
          @scope[:blocks]  = recover[:block]
280 281 282 283 284 285 286
        end

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

        def namespace(path)
287
          scope(path.to_s, :name_prefix => path.to_s, :namespace => path.to_s) { yield }
288 289 290 291 292 293 294 295 296 297 298
        end

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

        def match(*args)
          options = args.extract_options!

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

299 300
          if @scope[:name_prefix] && !options[:as].blank?
            options[:as] = "#{@scope[:name_prefix]}_#{options[:as]}"
301
          elsif @scope[:name_prefix] && options[:as] == ""
302
            options[:as] = @scope[:name_prefix].to_s
303 304 305 306 307
          end

          args.push(options)
          super(*args)
        end
308 309 310 311 312 313 314

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

          def merge_path_scope(parent, child)
315
            Mapper.normalize_path("#{parent}/#{child}")
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
          end

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

          def merge_namespace_scope(parent, child)
            parent ? "#{parent}/#{child}" : child
          end

          def merge_controller_scope(parent, child)
            @scope[:namespace] ? "#{@scope[:namespace]}/#{child}" : child
          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

          def merge_blocks_scope(parent, child)
            (parent || []) + [child]
          end

          def merge_options_scope(parent, child)
            (parent || {}).merge(child)
          end
345 346
      end

J
Joshua Peek 已提交
347
      module Resources
348
        CRUD_ACTIONS = [:index, :show, :create, :update, :destroy]
349

350
        class Resource #:nodoc:
351 352 353 354 355
          def self.default_actions
            [:index, :create, :new, :show, :update, :destroy, :edit]
          end

          attr_reader :plural, :singular, :options
356 357 358

          def initialize(entities, options = {})
            entities = entities.to_s
359
            @options = options
360 361 362 363 364

            @plural   = entities.pluralize
            @singular = entities.singularize
          end

365 366 367 368 369 370 371 372 373 374 375 376 377 378
          def default_actions
            self.class.default_actions
          end

          def actions
            if only = options[:only]
              only.map(&:to_sym)
            elsif except = options[:except]
              default_actions - except.map(&:to_sym)
            else
              default_actions
            end
          end

379 380 381 382 383 384 385 386 387
          def action_type(action)
            case action
            when :index, :create
              :collection
            when :show, :update, :destroy
              :member
            end
          end

388
          def name
389
            options[:as] || plural
390 391 392
          end

          def controller
393
            options[:controller] || plural
394 395 396
          end

          def member_name
397
            singular
398 399 400
          end

          def collection_name
401
            plural
402
          end
403

404 405 406 407 408 409 410 411 412
          def name_for_action(action)
            case action_type(action)
            when :collection
              collection_name
            when :member
              member_name
            end
          end

413 414 415
          def id_segment
            ":#{singular}_id"
          end
416 417 418
        end

        class SingletonResource < Resource #:nodoc:
419 420 421 422
          def self.default_actions
            [:show, :create, :update, :destroy, :new, :edit]
          end

423
          def initialize(entity, options = {})
424
            super
425 426
          end

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

434
          def name
435
            options[:as] || singular
436 437 438
          end
        end

439 440 441 442 443
        def initialize(*args)
          super
          @scope[:resources_path_names] = @set.resources_path_names
        end

J
Joshua Peek 已提交
444
        def resource(*resources, &block)
J
Joshua Peek 已提交
445
          options = resources.extract_options!
J
Joshua Peek 已提交
446

447
          if verify_common_behavior_for(:resource, resources, options, &block)
448 449 450
            return self
          end

451
          resource = SingletonResource.new(resources.pop, options)
452

453
          scope(:path => resource.name.to_s, :controller => resource.controller) do
454 455 456
            with_scope_level(:resource, resource) do
              yield if block_given?

457
              get    :show if resource.actions.include?(:show)
458 459 460
              post   :create if resource.actions.include?(:create)
              put    :update if resource.actions.include?(:update)
              delete :destroy if resource.actions.include?(:destroy)
461 462
              get    :new, :as => resource.singular if resource.actions.include?(:new)
              get    :edit, :as => resource.singular if resource.actions.include?(:edit)
463 464 465
            end
          end

J
Joshua Peek 已提交
466
          self
467 468
        end

J
Joshua Peek 已提交
469
        def resources(*resources, &block)
J
Joshua Peek 已提交
470
          options = resources.extract_options!
471

472
          if verify_common_behavior_for(:resources, resources, options, &block)
473 474 475
            return self
          end

476
          resource = Resource.new(resources.pop, options)
477

478
          scope(:path => resource.name.to_s, :controller => resource.controller) do
479 480
            with_scope_level(:resources, resource) do
              yield if block_given?
J
Joshua Peek 已提交
481

482
              with_scope_level(:collection) do
483
                get  :index if resource.actions.include?(:index)
484 485
                post :create if resource.actions.include?(:create)
                get  :new, :as => resource.singular if resource.actions.include?(:new)
486
              end
487

488
              with_scope_level(:member) do
489
                scope(':id') do
490
                  get    :show if resource.actions.include?(:show)
491 492 493
                  put    :update if resource.actions.include?(:update)
                  delete :destroy if resource.actions.include?(:destroy)
                  get    :edit, :as => resource.singular if resource.actions.include?(:edit)
J
Joshua Peek 已提交
494
                end
495 496 497 498
              end
            end
          end

J
Joshua Peek 已提交
499
          self
500 501
        end

J
Joshua Peek 已提交
502 503 504
        def collection
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use collection outside resources scope"
505 506
          end

J
Joshua Peek 已提交
507
          with_scope_level(:collection) do
508
            scope(:name_prefix => parent_resource.collection_name, :as => "") do
509 510
              yield
            end
J
Joshua Peek 已提交
511
          end
512
        end
J
Joshua Peek 已提交
513

J
Joshua Peek 已提交
514 515 516 517
        def member
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use member outside resources scope"
          end
J
Joshua Peek 已提交
518

J
Joshua Peek 已提交
519
          with_scope_level(:member) do
520
            scope(':id', :name_prefix => parent_resource.member_name, :as => "") do
J
Joshua Peek 已提交
521 522 523
              yield
            end
          end
J
Joshua Peek 已提交
524 525
        end

526 527 528 529 530 531
        def nested
          unless @scope[:scope_level] == :resources
            raise ArgumentError, "can't use nested outside resources scope"
          end

          with_scope_level(:nested) do
532
            scope(parent_resource.id_segment, :name_prefix => parent_resource.member_name) do
533 534 535 536 537
              yield
            end
          end
        end

J
Joshua Peek 已提交
538
        def match(*args)
J
Joshua Peek 已提交
539
          options = args.extract_options!
540 541 542 543 544 545

          if args.length > 1
            args.each { |path| match(path, options) }
            return self
          end

546 547
          resources_path_names = options.delete(:path_names)

548
          if args.first.is_a?(Symbol)
549 550
            action = args.first
            if CRUD_ACTIONS.include?(action)
551 552 553
              begin
                old_path = @scope[:path]
                @scope[:path] = "#{@scope[:path]}(.:format)"
554 555 556 557
                return match(options.reverse_merge(
                  :to => action,
                  :as => parent_resource.name_for_action(action)
                ))
558 559 560
              ensure
                @scope[:path] = old_path
              end
561 562
            else
              with_exclusive_name_prefix(action) do
563
                return match("#{action_path(action, resources_path_names)}(.:format)", options.reverse_merge(:to => action))
564
              end
565 566 567
            end
          end

J
Joshua Peek 已提交
568
          args.push(options)
J
Joshua Peek 已提交
569

J
Joshua Peek 已提交
570 571 572 573 574 575
          case options.delete(:on)
          when :collection
            return collection { match(*args) }
          when :member
            return member { match(*args) }
          end
J
Joshua Peek 已提交
576

J
Joshua Peek 已提交
577 578 579
          if @scope[:scope_level] == :resources
            raise ArgumentError, "can't define route directly in resources scope"
          end
J
Joshua Peek 已提交
580

J
Joshua Peek 已提交
581
          super
J
Joshua Peek 已提交
582 583
        end

584 585 586 587 588
        protected
          def parent_resource
            @scope[:scope_level_resource]
          end

J
Joshua Peek 已提交
589
        private
590 591 592 593 594
          def action_path(name, path_names = nil)
            path_names ||= @scope[:resources_path_names]
            path_names[name.to_sym] || name.to_s
          end

595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
          def verify_common_behavior_for(method, resources, options, &block)
            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

618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
          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

634
          def with_scope_level(kind, resource = parent_resource)
J
Joshua Peek 已提交
635
            old, @scope[:scope_level] = @scope[:scope_level], kind
636
            old_resource, @scope[:scope_level_resource] = @scope[:scope_level_resource], resource
J
Joshua Peek 已提交
637 638 639
            yield
          ensure
            @scope[:scope_level] = old
640
            @scope[:scope_level_resource] = old_resource
J
Joshua Peek 已提交
641 642
          end
      end
J
Joshua Peek 已提交
643

644 645 646 647
      include Base
      include HttpHelpers
      include Scoping
      include Resources
J
Joshua Peek 已提交
648 649
    end
  end
J
Joshua Peek 已提交
650
end