Class: Cybertrain::Gen::Mapper
- Inherits:
-
Object
- Object
- Cybertrain::Gen::Mapper
- Defined in:
- cybertrain/generator/routes_dsl.rb
Overview
The receiver of the routes DSL. Routes.draw evaluates its block with
the mapper as self; blocks nested inside it (namespace, scope,
resources, resource, member, collection) take the mapper as their
argument instead (resources :posts do |posts| posts.resources
:comments end), see Routes.draw for why.
The methods available in config/routes.rb. They run when
spin run gen generates gen/routes.rb, not in the server, so a
mistake is an ArgumentError from spin run gen. Routes match in the
order drawn; HEAD matches GET routes; an unmatched request is a plain
404 Not Found.
Each named route gets a <name>_path and a <name>_url helper (see
Gen::UrlHelpers). Not available: match, constraints, mount,
shallow, concerns, globs and optional segments; namespace and
scope are drawn outside resources blocks only.
Instance Method Summary collapse
-
#collection {|mapper| ... } ⇒ nil
Inside resources: get “search” -> GET /posts/search as search_posts.
-
#delete(path, to: "", as: "", on: nil, format: true) ⇒ nil
A DELETE route; see #get.
-
#get(path, to: "", as: "", on: nil, format: true) ⇒ nil
A GET route.
-
#jobs_page(path, before_action: "", skip_before_action: "") ⇒ nil
The jobs page (JobsPage): failed, discarded, running and queued jobs, with retry / discard / delete buttons, served by a generated
CybertrainJobsController < ApplicationController, so the application’s layout, CSRF protection andbefore_action:apply. -
#member {|mapper| ... } ⇒ nil
Inside resources or resource: get “preview” -> GET /posts/:id/preview as preview_post.
-
#namespace(name) {|mapper| ... } ⇒ nil
Routes whose paths, helper names and controllers sit under
name:scope "/admin", module: "admin", as: "admin", as in Rails. -
#patch(path, to: "", as: "", on: nil, format: true) ⇒ nil
A PATCH route; see #get.
-
#post(path, to: "", as: "", on: nil, format: true) ⇒ nil
A POST route; see #get.
-
#put(path, to: "", as: "", on: nil, format: true) ⇒ nil
A PUT route; see #get.
-
#redirect(path, status: 301) ⇒ RedirectSpec
A redirect, for
to:: the route answersstatuswithLocation: path, each%{name}inpathreplaced by the route’s:namesegment, escaped, and an empty body. -
#resource(name, only: nil, except: nil, controller: "", format: true) {|mapper| ... } ⇒ nil
A singular resource, one the visitor has at most one of (their session, their profile): the six actions without
index, at a path without an id, handled by the plural controller as in Rails. -
#resources(name, only: nil, except: nil, controller: "", param: :id, format: true) {|mapper| ... } ⇒ nil
The seven standard actions (only:/except: pick some).
-
#root(to, format: true) ⇒ nil
root “posts#index” -> GET / named “root”.
-
#scope(path = "", module: "", as: "") {|mapper| ... } ⇒ nil
Routes under a path prefix, a controller module and a helper-name prefix, each optional, as in Rails:
scope "dashboard"changes the paths only (/dashboard/stats),scope module: "admin"the controllers only (admin/users, Admin::UsersController),scope as: "admin"the helper names only (admin_stats_path).
Instance Method Details
#collection {|mapper| ... } ⇒ nil
Inside resources: get “search” -> GET /posts/search as search_posts.
618 619 620 |
# File 'cybertrain/generator/routes_dsl.rb', line 618 def collection(&block) within("collection", block) end |
#delete(path, to: "", as: "", on: nil, format: true) ⇒ nil
A DELETE route; see #get.
252 253 254 |
# File 'cybertrain/generator/routes_dsl.rb', line 252 def delete(path, to: "", as: "", on: nil, format: true) add_custom_route("DELETE", path, to, as, on, format) end |
#get(path, to: "", as: "", on: nil, format: true) ⇒ nil
A GET route. At the top level to: is required; inside a
resources or resource block (or a member / collection) the
controller is the resource’s and the action defaults to the path.
The name is as:, or the path with every character outside
[a-z0-9_] turned into _ ("about-us" → about_us). Inside a
member block (or with on: :member) it gets the resource’s
singular as a suffix (preview_post), inside collection (or with
on: :collection) the plural (search_posts), inside resources
its prefix (post_...); a namespace or scope as: prefixes it too
(admin_stats). A derived name that an earlier route already took
leaves the route unnamed, as in Rails (get "/sign_up" then post
"/sign_up": one sign_up_path); a duplicate as: is an error.
Inside a namespace or scope module: the controller of to: gets
the module (to: "stats#index" → admin/stats).
204 205 206 |
# File 'cybertrain/generator/routes_dsl.rb', line 204 def get(path, to: "", as: "", on: nil, format: true) add_custom_route("GET", path, to, as, on, format) end |
#jobs_page(path, before_action: "", skip_before_action: "") ⇒ nil
The jobs page (JobsPage): failed, discarded, running
and queued jobs, with retry / discard / delete buttons, served by a
generated CybertrainJobsController < ApplicationController, so the
application’s layout, CSRF protection and before_action: apply.
Draws, to that controller:
| Verb | Path | Action |
|---|---|---|
| GET | path |
index (?page=N) |
| POST | path/retry_all |
retry_all (every failed job) |
| POST | path/discard_all |
discard_all_failed |
| POST | path/:id/retry |
retry |
| POST | path/:id/discard |
discard |
| POST | path/:id/delete |
delete |
The routes are unnamed (no *_path helpers). One jobs page per
application, drawn at the top level or inside a namespace or a
scope, whose path prefix it takes (admin.jobs_page "/jobs" is
/admin/jobs; the controller stays CybertrainJobsController).
Without before_action: the page is open to anyone who can reach
it, and spin run gen prints a warning saying so. The guard runs
after the callbacks ApplicationController declares (Rails’ order),
so with generate authentication a visitor is sent to sign in
first; skip_before_action: :require_authentication leaves that
one out, so the guard alone decides (require_admin answers a
visitor 404, as if there were no page). Only the callback named is
skipped, and only when this option says so.
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
# File 'cybertrain/generator/routes_dsl.rb', line 375 def jobs_page(path, before_action: "", skip_before_action: "") raise ArgumentError, "jobs_page must be used at the top of the routes, not inside resources" unless @mode == "top" guard = "#{before_action}" full = "#{@path_prefix}#{path}" [path, full].each do |candidate| next if jobs_page_path?(candidate) = "jobs_page #{candidate.inspect}: the path must start with \"/\" and be literal segments of letters, digits, _ and -" raise ArgumentError, end unless guard.empty? || guard.match?(ACTION_PATTERN) = "jobs_page #{path.inspect}: before_action: #{guard.inspect} is not a method name" raise ArgumentError, end skip = "#{skip_before_action}" unless skip.empty? at = jobs_page_location(path) unless skip.match?(ACTION_PATTERN) = "#{at}jobs_page #{path.inspect}: skip_before_action: #{skip.inspect} is not a method name" raise ArgumentError, end if guard.empty? = "#{at}jobs_page #{path.inspect}: skip_before_action: :#{skip} needs a before_action: that decides " \ "who sees the page; without one it would open the page to everyone" raise ArgumentError, end if guard == skip = "#{at}jobs_page #{path.inspect}: skip_before_action: :#{skip} is the page's own before_action:; " \ "skipping it would open the page to everyone" raise ArgumentError, end end Cybertrain::Routes.record_jobs_page(full, guard, skip) controller = "cybertrain_jobs" add_jobs_route("GET", full, controller, "index", "index") add_jobs_route("POST", "#{full}/retry_all", controller, "retry_all", "retry_all_action") add_jobs_route("POST", "#{full}/discard_all", controller, "discard_all_failed", "discard_all_failed_action") add_jobs_route("POST", "#{full}/:id/retry", controller, "retry", "retry_action") add_jobs_route("POST", "#{full}/:id/discard", controller, "discard", "discard_action") add_jobs_route("POST", "#{full}/:id/delete", controller, "delete", "delete_action") nil end |
#member {|mapper| ... } ⇒ nil
Inside resources or resource: get “preview” -> GET /posts/:id/preview as preview_post.
609 610 611 |
# File 'cybertrain/generator/routes_dsl.rb', line 609 def member(&block) within("member", block) end |
#namespace(name) {|mapper| ... } ⇒ nil
Routes whose paths, helper names and controllers sit under name:
scope "/admin", module: "admin", as: "admin", as in Rails.
Namespaces nest.
namespace :admin do |admin| admin.resources :articles end draws
/admin/articles to Admin::ArticlesController
(app/controllers/admin/articles_controller.rb, written module
Admin; class ArticlesController or class Admin::ArticlesController),
with admin_articles_path and admin_article_path(article); its
views are in app/views/admin/articles/.
300 301 302 303 304 305 |
# File 'cybertrain/generator/routes_dsl.rb', line 300 def namespace(name, &block) raise ArgumentError, "namespace must be used outside resources" unless @mode == "top" word = "#{name}" within_scope(word, word, word, block) end |
#patch(path, to: "", as: "", on: nil, format: true) ⇒ nil
A PATCH route; see #get.
228 229 230 |
# File 'cybertrain/generator/routes_dsl.rb', line 228 def patch(path, to: "", as: "", on: nil, format: true) add_custom_route("PATCH", path, to, as, on, format) end |
#post(path, to: "", as: "", on: nil, format: true) ⇒ nil
A POST route; see #get.
216 217 218 |
# File 'cybertrain/generator/routes_dsl.rb', line 216 def post(path, to: "", as: "", on: nil, format: true) add_custom_route("POST", path, to, as, on, format) end |
#put(path, to: "", as: "", on: nil, format: true) ⇒ nil
A PUT route; see #get.
240 241 242 |
# File 'cybertrain/generator/routes_dsl.rb', line 240 def put(path, to: "", as: "", on: nil, format: true) add_custom_route("PUT", path, to, as, on, format) end |
#redirect(path, status: 301) ⇒ RedirectSpec
A redirect, for to:: the route answers status with Location:
path, each %{name} in path replaced by the route’s :name
segment, escaped, and an empty body. A redirect route is unnamed
unless given as:. The block form that computes the target is not
available (a controller action does that).
270 271 272 273 274 275 276 277 |
# File 'cybertrain/generator/routes_dsl.rb', line 270 def redirect(path, status: 301) code = status.to_i unless code >= 300 && code <= 308 = "redirect status: must be a 3xx code (got #{code})" raise ArgumentError, end RedirectSpec.new("#{path}", code) end |
#resource(name, only: nil, except: nil, controller: "", format: true) {|mapper| ... } ⇒ nil
A singular resource, one the visitor has at most one of (their
session, their profile): the six actions without index, at a path
without an id, handled by the plural controller as in Rails.
resource :session draws, to SessionsController:
| Verb | Path | Action | Helper |
|---|---|---|---|
| GET | /session/new |
new (def new_action) |
new_session_path |
| POST | /session |
create |
session_path |
| GET | /session/edit |
edit |
edit_session_path |
| GET | /session |
show |
|
| PATCH, PUT | /session |
update |
|
| DELETE | /session |
destroy |
The order is Rails’ (new before show, so /session/new is not
read as a member). controller: names another controller. A block
draws member routes (get :refresh, on: :member or a member
block: /session/refresh, refresh_session_path) and nested
singular or plural resources (/session/settings/edit,
edit_session_settings_path), before the resource’s own.
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 |
# File 'cybertrain/generator/routes_dsl.rb', line 560 def resource(name, only: nil, except: nil, controller: "", format: true, &block) singular = "#{name}" given = "#{controller}" target = @module_prefix + (given.empty? ? Inflector.pluralize(singular) : given) path = "#{@path_prefix}/#{singular}" route_name = @name_prefix + singular args = @prefix_args unless block.nil? saved = save_scope @mode = "resource" @path_prefix = path @name_prefix = route_name + "_" @controller = target @member_path = path @member_name = route_name @member_args = args @collection_path = "" @collection_name = "" @collection_args = "" block.call(self) restore_scope(saved) end used = [] SINGULAR_ACTIONS.each do |action| next unless only.nil? || only.include?(action) next if !except.nil? && except.include?(action) case action when :create then add_standard(used, "POST", path, target, "create", route_name, args, format) when :new then add_standard(used, "GET", "#{path}/new", target, "new", "new_#{route_name}", args, format) when :edit then add_standard(used, "GET", "#{path}/edit", target, "edit", "edit_#{route_name}", args, format) when :show then add_standard(used, "GET", path, target, "show", route_name, args, format) when :update add_standard(used, "PATCH", path, target, "update", route_name, args, format) add_standard(used, "PUT", path, target, "update", route_name, args, format) when :destroy then add_standard(used, "DELETE", path, target, "destroy", route_name, args, format) end end nil end |
#resources(name, only: nil, except: nil, controller: "", param: :id, format: true) {|mapper| ... } ⇒ nil
The seven standard actions (only:/except: pick some). Routes drawn in the block (nested resources, member, collection) come first, so /posts/search wins over /posts/:id as in Rails.
resources :articles draws, to ArticlesController:
| Verb | Path | Action | Helper |
|---|---|---|---|
| GET | /articles |
index |
articles_path |
| POST | /articles |
create |
|
| GET | /articles/new |
new (def new_action) |
new_article_path |
| GET | /articles/:id/edit |
edit |
edit_article_path(article) |
| GET | /articles/:id |
show |
article_path(article) |
| PATCH, PUT | /articles/:id |
update |
|
| DELETE | /articles/:id |
destroy |
A word that is its own plural (sheep) names the collection
sheep_index. Nested resources take the parent’s id as
:<singular>_id and its singular as a name prefix:
article_comments_path(article), article_comment_path(article,
comment). Their controller is the child’s (CommentsController).
controller: names another controller; param: another segment
than :id (resources :indicators, param: :key: /indicators/:key,
params[:key], nested resources under :indicator_key); the
helpers still take the record (indicator_path(indicator), which
reads indicator.to_param).
465 466 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 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 |
# File 'cybertrain/generator/routes_dsl.rb', line 465 def resources(name, only: nil, except: nil, controller: "", param: :id, format: true, &block) # Interpolated, not name.to_s: in a program that also loads the model # runtime, name.to_s came out boxed and widened @controller, which # broke the C build of save_scope/restore_scope. plural = "#{name}" singular = Inflector.singularize(plural) key = "#{param}" unless key.match?(PARAM_PATTERN) = "param: must be a lowercase name (got #{key.inspect})" raise ArgumentError, end given = "#{controller}" target = @module_prefix + (given.empty? ? plural : given) collection_path = "#{@path_prefix}/#{plural}" member_path = "#{collection_path}/:#{key}" member_name = @name_prefix + singular member_args = join_args(@prefix_args, singular) collection_args = @prefix_args # A word whose singular is itself (sheep, news) would give index and # show the same name; Rails names the collection news_index. collection_name = @name_prefix + plural + (singular == plural ? "_index" : "") unless block.nil? saved = save_scope @mode = "resources" @path_prefix = "#{collection_path}/:#{singular}_#{key}" @prefix_args = member_args @name_prefix = member_name + "_" @controller = target @member_path = member_path @member_name = member_name @member_args = member_args @collection_path = collection_path @collection_name = collection_name @collection_args = collection_args block.call(self) restore_scope(saved) end used = [] STANDARD_ACTIONS.each do |action| next unless only.nil? || only.include?(action) next if !except.nil? && except.include?(action) case action when :index then add_standard(used, "GET", collection_path, target, "index", collection_name, collection_args, format) when :create then add_standard(used, "POST", collection_path, target, "create", collection_name, collection_args, format) when :new then add_standard(used, "GET", "#{collection_path}/new", target, "new", "new_#{member_name}", collection_args, format) when :edit then add_standard(used, "GET", "#{member_path}/edit", target, "edit", "edit_#{member_name}", member_args, format) when :show then add_standard(used, "GET", member_path, target, "show", member_name, member_args, format) when :update add_standard(used, "PATCH", member_path, target, "update", member_name, member_args, format) add_standard(used, "PUT", member_path, target, "update", member_name, member_args, format) when :destroy then add_standard(used, "DELETE", member_path, target, "destroy", member_name, member_args, format) end end nil end |
#root(to, format: true) ⇒ nil
root “posts#index” -> GET / named “root”. Inside a namespace or a
scope it takes the prefixes (namespace :admin do |admin|
admin.root "dashboard#index" end: GET /admin, admin_root_path,
Admin::DashboardController).
158 159 160 161 162 |
# File 'cybertrain/generator/routes_dsl.rb', line 158 def root(to, format: true) target = split_to(to) path = @path_prefix.empty? ? "/" : @path_prefix add_spec("GET", path, @module_prefix + target[0], target[1], "#{@name_prefix}root", @prefix_args, format) end |
#scope(path = "", module: "", as: "") {|mapper| ... } ⇒ nil
Routes under a path prefix, a controller module and a helper-name
prefix, each optional, as in Rails: scope "dashboard" changes the
paths only (/dashboard/stats), scope module: "admin" the
controllers only (admin/users, Admin::UsersController), scope as:
"admin" the helper names only (admin_stats_path). They combine
(scope "/x", module: "y", as: "z"). A :name segment in the path
becomes a param and a helper argument (scope "/:locale").
325 326 327 328 329 330 |
# File 'cybertrain/generator/routes_dsl.rb', line 325 def scope(path = "", module: "", as: "", &block) raise ArgumentError, "scope must be used outside resources" unless @mode == "top" mod = "#{binding.local_variable_get(:module)}" within_scope("#{path}", mod, "#{as}", block) end |