instance method scope

Ruby on Rails 4.1.16

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

scope(*args)

Scopes a set of routes to the given default options.

Take the following route definition as an example:

scope path: ":account_id", as: "account" do
  resources :projects
end

This generates helpers such as account_projects_path, just like resources does. The difference here being that the routes generated are like /:account_id/projects, rather than /accounts/:account_id/projects.

Options

Takes same options as Base#match and Resources#resources.

# route /posts (without the prefix /admin) to <tt>Admin::PostsController</tt>
scope module: "admin" do
  resources :posts
end

# prefix the posts resource's requests with '/admin'
scope path: "/admin" do
  resources :posts
end

# prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+
scope as: "sekret" do
  resources :posts
end

Parameters

args rest
Source
# File actionpack/lib/action_dispatch/routing/mapper.rb, line 726
        def scope(*args)
          options = args.extract_options!.dup
          recover = {}

          options[:path] = args.flatten.join('/') if args.any?
          options[:constraints] ||= {}

          unless nested_scope?
            options[:shallow_path] ||= options[:path] if options.key?(:path)
            options[:shallow_prefix] ||= options[:as] if options.key?(:as)
          end

          if options[:constraints].is_a?(Hash)
            defaults = options[:constraints].select do
              |k, v| URL_OPTIONS.include?(k) && (v.is_a?(String) || v.is_a?(Fixnum))
            end

            (options[:defaults] ||= {}).reverse_merge!(defaults)
          else
            block, options[:constraints] = options[:constraints], {}
          end

          SCOPE_OPTIONS.each do |option|
            if option == :blocks
              value = block
            elsif option == :options
              value = options
            else
              value = options.delete(option)
            end

            if value
              recover[option] = @scope[option]
              @scope[option]  = send("merge_#{option}_scope", @scope[option], value)
            end
          end

          yield
          self
        ensure
          @scope.merge!(recover)
        end

Defined in actionpack/lib/action_dispatch/routing/mapper.rb line 726 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionDispatch::Routing::Mapper::Scoping

Type at least 2 characters to search.

↑↓ navigate · open · esc close