Class: ActionDispatch::Routing::RouteSet

Inherits:
Object
  • Object
show all
Defined in:
lib/action_dispatch/routing/route_set.rb

Overview

:stopdoc:

Defined Under Namespace

Modules: MountedHelpers Classes: Config, CustomUrlHelper, Dispatcher, Generator, NamedRouteCollection, StaticDispatcher

Constant Summary collapse

PATH =

strategy for building urls to send to the client

->(options) { ActionDispatch::Http::URL.path_for(options) }
UNKNOWN =
->(options) { ActionDispatch::Http::URL.url_for(options) }
DEFAULT_CONFIG =
Config.new(nil, false)
RESERVED_OPTIONS =
[:host, :protocol, :port, :subdomain, :domain, :tld_length,
:trailing_slash, :anchor, :params, :only_path, :script_name,
:original_script_name, :relative_url_root]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = DEFAULT_CONFIG) ⇒ RouteSet

Returns a new instance of RouteSet.



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/action_dispatch/routing/route_set.rb', line 371

def initialize(config = DEFAULT_CONFIG)
  self.named_routes = NamedRouteCollection.new
  self.resources_path_names = self.class.default_resources_path_names
  self.default_url_options = {}

  @config                     = config
  @append                     = []
  @prepend                    = []
  @disable_clear_and_finalize = false
  @finalized                  = false
  @env_key                    = "ROUTES_#{object_id}_SCRIPT_NAME".freeze

  @set    = Journey::Routes.new
  @router = Journey::Router.new @set
  @formatter = Journey::Formatter.new self
  @polymorphic_mappings = {}
end

Instance Attribute Details

#default_scopeObject

Returns the value of attribute default_scope.



341
342
343
# File 'lib/action_dispatch/routing/route_set.rb', line 341

def default_scope
  @default_scope
end

#default_url_optionsObject

Returns the value of attribute default_url_options.



343
344
345
# File 'lib/action_dispatch/routing/route_set.rb', line 343

def default_url_options
  @default_url_options
end

#disable_clear_and_finalizeObject

Returns the value of attribute disable_clear_and_finalize.



342
343
344
# File 'lib/action_dispatch/routing/route_set.rb', line 342

def disable_clear_and_finalize
  @disable_clear_and_finalize
end

#env_keyObject (readonly)

Returns the value of attribute env_key.



344
345
346
# File 'lib/action_dispatch/routing/route_set.rb', line 344

def env_key
  @env_key
end

#formatterObject

Returns the value of attribute formatter.



341
342
343
# File 'lib/action_dispatch/routing/route_set.rb', line 341

def formatter
  @formatter
end

#named_routesObject

Returns the value of attribute named_routes.



341
342
343
# File 'lib/action_dispatch/routing/route_set.rb', line 341

def named_routes
  @named_routes
end

#polymorphic_mappingsObject (readonly)

Returns the value of attribute polymorphic_mappings.



344
345
346
# File 'lib/action_dispatch/routing/route_set.rb', line 344

def polymorphic_mappings
  @polymorphic_mappings
end

#resources_path_namesObject

Returns the value of attribute resources_path_names.



342
343
344
# File 'lib/action_dispatch/routing/route_set.rb', line 342

def resources_path_names
  @resources_path_names
end

#routerObject

Returns the value of attribute router.



341
342
343
# File 'lib/action_dispatch/routing/route_set.rb', line 341

def router
  @router
end

#setObject Also known as: routes

Returns the value of attribute set.



341
342
343
# File 'lib/action_dispatch/routing/route_set.rb', line 341

def set
  @set
end

Class Method Details

.default_resources_path_namesObject



348
349
350
# File 'lib/action_dispatch/routing/route_set.rb', line 348

def self.default_resources_path_names
  { new: "new", edit: "edit" }
end

.new_with_config(config) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/action_dispatch/routing/route_set.rb', line 352

def self.new_with_config(config)
  route_set_config = DEFAULT_CONFIG

  # engines apparently don't have this set
  if config.respond_to? :relative_url_root
    route_set_config.relative_url_root = config.relative_url_root
  end

  if config.respond_to? :api_only
    route_set_config.api_only = config.api_only
  end

  new route_set_config
end

Instance Method Details

#add_polymorphic_mapping(klass, options, &block) ⇒ Object



611
612
613
# File 'lib/action_dispatch/routing/route_set.rb', line 611

def add_polymorphic_mapping(klass, options, &block)
  @polymorphic_mappings[klass] = CustomUrlHelper.new(klass, options, &block)
end

#add_route(mapping, name) ⇒ Object

Raises:

  • (ArgumentError)


580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/action_dispatch/routing/route_set.rb', line 580

def add_route(mapping, name)
  raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)

  if name && named_routes[name]
    raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \
      "You may have defined two routes with the same name using the `:as` option, or " \
      "you may be overriding a route already defined by a resource with the same naming. " \
      "For the latter, you can restrict the routes created with `resources` as explained here: \n" \
      "http://guides.rubyonrails.org/routing.html#restricting-the-routes-created"
  end

  route = @set.add_route(name, mapping)
  named_routes[name] = route if name

  if route.segment_keys.include?(:controller)
    ActiveSupport::Deprecation.warn(<<-MSG.squish)
      Using a dynamic :controller segment in a route is deprecated and
      will be removed in Rails 6.0.
    MSG
  end

  if route.segment_keys.include?(:action)
    ActiveSupport::Deprecation.warn(<<-MSG.squish)
      Using a dynamic :action segment in a route is deprecated and
      will be removed in Rails 6.0.
    MSG
  end

  route
end

#add_url_helper(name, options, &block) ⇒ Object



615
616
617
# File 'lib/action_dispatch/routing/route_set.rb', line 615

def add_url_helper(name, options, &block)
  named_routes.add_url_helper(name, options, &block)
end

#api_only?Boolean

Returns:

  • (Boolean)


399
400
401
# File 'lib/action_dispatch/routing/route_set.rb', line 399

def api_only?
  @config.api_only
end

#append(&block) ⇒ Object



419
420
421
# File 'lib/action_dispatch/routing/route_set.rb', line 419

def append(&block)
  @append << block
end

#call(env) ⇒ Object



837
838
839
840
841
# File 'lib/action_dispatch/routing/route_set.rb', line 837

def call(env)
  req = make_request(env)
  req.path_info = Journey::Router::Utils.normalize_path(req.path_info)
  @router.serve(req)
end

#clear!Object



443
444
445
446
447
448
449
450
# File 'lib/action_dispatch/routing/route_set.rb', line 443

def clear!
  @finalized = false
  named_routes.clear
  set.clear
  formatter.clear
  @polymorphic_mappings.clear
  @prepend.each { |blk| eval_block(blk) }
end

#define_mounted_helper(name, script_namer = nil) ⇒ Object



465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/action_dispatch/routing/route_set.rb', line 465

def define_mounted_helper(name, script_namer = nil)
  return if MountedHelpers.method_defined?(name)

  routes = self
  helpers = routes.url_helpers

  MountedHelpers.class_eval do
    define_method "_#{name}" do
      RoutesProxy.new(routes, _routes_context, helpers, script_namer)
    end
  end

  MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
    def #{name}
      @_#{name} ||= _#{name}
    end
  RUBY
end

#draw(&block) ⇒ Object



412
413
414
415
416
417
# File 'lib/action_dispatch/routing/route_set.rb', line 412

def draw(&block)
  clear! unless @disable_clear_and_finalize
  eval_block(block)
  finalize! unless @disable_clear_and_finalize
  nil
end

#eager_load!Object



389
390
391
392
393
# File 'lib/action_dispatch/routing/route_set.rb', line 389

def eager_load!
  router.eager_load!
  routes.each(&:eager_load!)
  nil
end

#empty?Boolean

Returns:

  • (Boolean)


576
577
578
# File 'lib/action_dispatch/routing/route_set.rb', line 576

def empty?
  routes.empty?
end

#extra_keys(options, recall = {}) ⇒ Object

Generate the path indicated by the arguments, and return an array of the keys that were not used to generate it.



764
765
766
# File 'lib/action_dispatch/routing/route_set.rb', line 764

def extra_keys(options, recall = {})
  generate_extras(options, recall).last
end

#finalize!Object



437
438
439
440
441
# File 'lib/action_dispatch/routing/route_set.rb', line 437

def finalize!
  return if @finalized
  @append.each { |blk| eval_block(blk) }
  @finalized = true
end

#find_relative_url_root(options) ⇒ Object



791
792
793
# File 'lib/action_dispatch/routing/route_set.rb', line 791

def find_relative_url_root(options)
  options.delete(:relative_url_root) || relative_url_root
end

#find_script_name(options) ⇒ Object



787
788
789
# File 'lib/action_dispatch/routing/route_set.rb', line 787

def find_script_name(options)
  options.delete(:script_name) || find_relative_url_root(options) || ""
end

#generate_extras(options, recall = {}) ⇒ Object



768
769
770
771
772
# File 'lib/action_dispatch/routing/route_set.rb', line 768

def generate_extras(options, recall = {})
  route_key = options.delete :use_route
  path, params = generate(route_key, options, recall)
  return path, params.keys
end

#mounted_helpersObject

Contains all the mounted helpers across different engines and the `main_app` helper for the application. You can include this in your classes if you want to access routes for other engines.



461
462
463
# File 'lib/action_dispatch/routing/route_set.rb', line 461

def mounted_helpers
  MountedHelpers
end

#optimize_routes_generation?Boolean

Returns:

  • (Boolean)


783
784
785
# File 'lib/action_dispatch/routing/route_set.rb', line 783

def optimize_routes_generation?
  default_url_options.empty?
end

#path_for(options, route_name = nil) ⇒ Object



795
796
797
# File 'lib/action_dispatch/routing/route_set.rb', line 795

def path_for(options, route_name = nil)
  url_for(options, route_name, PATH)
end

#prepend(&block) ⇒ Object



423
424
425
# File 'lib/action_dispatch/routing/route_set.rb', line 423

def prepend(&block)
  @prepend << block
end

#recognize_path(path, environment = {}) ⇒ Object



843
844
845
846
847
848
849
850
851
852
853
854
855
856
# File 'lib/action_dispatch/routing/route_set.rb', line 843

def recognize_path(path, environment = {})
  method = (environment[:method] || "GET").to_s.upcase
  path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
  extras = environment[:extras] || {}

  begin
    env = Rack::MockRequest.env_for(path, method: method)
  rescue URI::InvalidURIError => e
    raise ActionController::RoutingError, e.message
  end

  req = make_request(env)
  recognize_path_with_request(req, path, extras)
end

#recognize_path_with_request(req, path, extras, raise_on_missing: true) ⇒ Object



858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
# File 'lib/action_dispatch/routing/route_set.rb', line 858

def recognize_path_with_request(req, path, extras, raise_on_missing: true)
  @router.recognize(req) do |route, params|
    params.merge!(extras)
    params.each do |key, value|
      if value.is_a?(String)
        value = value.dup.force_encoding(Encoding::BINARY)
        params[key] = URI.parser.unescape(value)
      end
    end
    req.path_parameters = params
    app = route.app
    if app.matches?(req) && app.dispatcher?
      begin
        req.controller_class
      rescue NameError
        raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller"
      end

      return req.path_parameters
    elsif app.matches?(req) && app.engine?
      path_parameters = app.rack_app.routes.recognize_path_with_request(req, path, extras, raise_on_missing: false)
      return path_parameters if path_parameters
    end
  end

  if raise_on_missing
    raise ActionController::RoutingError, "No route matches #{path.inspect}"
  end
end

#relative_url_rootObject



395
396
397
# File 'lib/action_dispatch/routing/route_set.rb', line 395

def relative_url_root
  @config.relative_url_root
end

#request_classObject



403
404
405
# File 'lib/action_dispatch/routing/route_set.rb', line 403

def request_class
  ActionDispatch::Request
end

#url_for(options, route_name = nil, url_strategy = UNKNOWN) ⇒ Object

The options argument must be a hash whose keys are symbols.



800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
# File 'lib/action_dispatch/routing/route_set.rb', line 800

def url_for(options, route_name = nil, url_strategy = UNKNOWN)
  options = default_url_options.merge options

  user = password = nil

  if options[:user] && options[:password]
    user     = options.delete :user
    password = options.delete :password
  end

  recall = options.delete(:_recall) { {} }

  original_script_name = options.delete(:original_script_name)
  script_name = find_script_name options

  if original_script_name
    script_name = original_script_name + script_name
  end

  path_options = options.dup
  RESERVED_OPTIONS.each { |ro| path_options.delete ro }

  path, params = generate(route_name, path_options, recall)

  if options.key? :params
    params.merge! options[:params]
  end

  options[:path]        = path
  options[:script_name] = script_name
  options[:params]      = params
  options[:user]        = user
  options[:password]    = password

  url_strategy.call options
end

#url_helpers(supports_path = true) ⇒ Object



484
485
486
487
488
489
490
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'lib/action_dispatch/routing/route_set.rb', line 484

def url_helpers(supports_path = true)
  routes = self

  Module.new do
    extend ActiveSupport::Concern
    include UrlFor

    # Define url_for in the singleton level so one can do:
    # Rails.application.routes.url_helpers.url_for(args)
    proxy_class = Class.new do
      include UrlFor
      include routes.named_routes.path_helpers_module
      include routes.named_routes.url_helpers_module

      attr_reader :_routes

      def initialize(routes)
        @_routes = routes
      end

      def optimize_routes_generation?
        @_routes.optimize_routes_generation?
      end
    end

    @_proxy = proxy_class.new(routes)

    class << self
      def url_for(options)
        @_proxy.url_for(options)
      end

      def full_url_for(options)
        @_proxy.full_url_for(options)
      end

      def route_for(name, *args)
        @_proxy.route_for(name, *args)
      end

      def optimize_routes_generation?
        @_proxy.optimize_routes_generation?
      end

      def polymorphic_url(record_or_hash_or_array, options = {})
        @_proxy.polymorphic_url(record_or_hash_or_array, options)
      end

      def polymorphic_path(record_or_hash_or_array, options = {})
        @_proxy.polymorphic_path(record_or_hash_or_array, options)
      end

      def _routes; @_proxy._routes; end
      def url_options; {}; end
    end

    url_helpers = routes.named_routes.url_helpers_module

    # Make named_routes available in the module singleton
    # as well, so one can do:
    # Rails.application.routes.url_helpers.posts_path
    extend url_helpers

    # Any class that includes this module will get all
    # named routes...
    include url_helpers

    if supports_path
      path_helpers = routes.named_routes.path_helpers_module

      include path_helpers
      extend path_helpers
    end

    # plus a singleton class method called _routes ...
    included do
      redefine_singleton_method(:_routes) { routes }
    end

    # And an instance method _routes. Note that
    # UrlFor (included in this module) add extra
    # conveniences for working with @_routes.
    define_method(:_routes) { @_routes || routes }

    define_method(:_generate_paths_by_default) do
      supports_path
    end

    private :_generate_paths_by_default
  end
end