Class: Cybertrain::Gen::Mapper

Inherits:
Object
  • Object
show all
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

Instance Method Details

#collection {|mapper| ... } ⇒ nil

Inside resources: get “search” -> GET /posts/search as search_posts.

Yield Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    outside a resources block



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.

Parameters:

  • path (String, Symbol)
  • to (String, RedirectSpec) (defaults to: "")
  • as (String) (defaults to: "")
  • on (Symbol, nil) (defaults to: nil)
  • format (Boolean) (defaults to: true)

Returns:

  • (nil)


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).

Examples:

get "/about", to: "pages#about"               # GET /about, about_path
get "/feed", to: "articles#index", as: "feed"   # feed_path
resources :posts do |posts|
  posts.get :search, on: :collection          # GET /posts/search, search_posts_path
  posts.post :publish, on: :member            # POST /posts/:id/publish, publish_post_path
end
get "/old", to: redirect("/new")                # 301 to /new

Parameters:

  • path (String, Symbol) —

    :name segments become params ("/users/:id")

  • to (String, RedirectSpec) (defaults to: "") —

    "controller#action", just "action", or a #redirect

  • as (String) (defaults to: "") —

    the route name

  • on (Symbol, nil) (defaults to: nil) —

    :member (inside resources or resource) or :collection (inside resources): as in a member / collection block

  • format (Boolean) (defaults to: true) —

    false: the route matches no .:format extension, so a dot in the last segment is part of it (get "/files/:name", to: "files#show", format: false gives params[:name] == "report.v2")

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    with no controller, an invalid or duplicate name, an on: that does not fit where the route is drawn, or a redirect whose %{name} is not a segment of the path



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.

Examples:

jobs_page "/admin/jobs", before_action: :require_admin
jobs_page "/admin/jobs", before_action: :require_admin, skip_before_action: :require_authentication

Parameters:

  • path (String) —

    literal segments ("/admin/jobs")

  • before_action (Symbol, String) (defaults to: "") —

    a method of ApplicationController that renders or redirects to refuse the visitor (:require_admin)

  • skip_before_action (Symbol, String) (defaults to: "") —

    an inherited before callback the page does not run (:require_authentication); needs a before_action: other than itself

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    for a second jobs page, one inside resources, a path with dynamic or empty segments, a before_action or skip_before_action that is not a method name, a skip_before_action without a before_action or naming the same method (either would open the page to everyone)



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)

    message = "jobs_page #{candidate.inspect}: the path must start with \"/\" and be literal segments of letters, digits, _ and -"
    raise ArgumentError, message
  end
  unless guard.empty? || guard.match?(ACTION_PATTERN)
    message = "jobs_page #{path.inspect}: before_action: #{guard.inspect} is not a method name"
    raise ArgumentError, message
  end
  skip = "#{skip_before_action}"
  unless skip.empty?
    at = jobs_page_location(path)
    unless skip.match?(ACTION_PATTERN)
      message = "#{at}jobs_page #{path.inspect}: skip_before_action: #{skip.inspect} is not a method name"
      raise ArgumentError, message
    end
    if guard.empty?
      message = "#{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, message
    end
    if guard == skip
      message = "#{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, message
    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.

Yield Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    outside a resources or resource block



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/.

Examples:

namespace :admin do |admin|
  admin.resources :articles, only: [:index, :destroy]
  admin.jobs_page "/jobs", before_action: :require_admin   # /admin/jobs
end

Parameters:

  • name (Symbol) —

    the namespace (:admin)

Yield Parameters:

  • mapper (Mapper) —

    the mapper, to call with an explicit receiver inside the block (admin.resources)

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    inside resources or resource



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.

Parameters:

  • path (String, Symbol)
  • to (String, RedirectSpec) (defaults to: "")
  • as (String) (defaults to: "")
  • on (Symbol, nil) (defaults to: nil)
  • format (Boolean) (defaults to: true)

Returns:

  • (nil)


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.

Parameters:

  • path (String, Symbol)
  • to (String, RedirectSpec) (defaults to: "")
  • as (String) (defaults to: "")
  • on (Symbol, nil) (defaults to: nil)
  • format (Boolean) (defaults to: true)

Returns:

  • (nil)


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.

Parameters:

  • path (String, Symbol)
  • to (String, RedirectSpec) (defaults to: "")
  • as (String) (defaults to: "")
  • on (Symbol, nil) (defaults to: nil)
  • format (Boolean) (defaults to: true)

Returns:

  • (nil)


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).

Examples:

get "/old", to: redirect("/new")                                   # 301
get "/posts/:id/show", to: redirect("/posts/%{id}", status: 302)

Parameters:

  • path (String) —

    the target, a path or URL

  • status (Integer) (defaults to: 301) —

    300 to 308

Returns:

Raises:

  • (ArgumentError) —

    for a status outside 300-308 (the route raises for a %{name} its path lacks)



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
    message = "redirect status: must be a 3xx code (got #{code})"
    raise ArgumentError, message
  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.

Examples:

resource :session, controller: "auth/sessions" do |session|
  session.get :refresh, on: :member
  session.resource :settings, only: [:edit, :update]
end

Parameters:

  • name (Symbol) —

    the singular (:session)

  • only (Array<Symbol>, nil) (defaults to: nil) —

    draw only these actions

  • except (Array<Symbol>, nil) (defaults to: nil) —

    draw all but these

  • controller (String) (defaults to: "") —

    the controller ("auth/sessions"), under the enclosing namespace’s module; default the plural

  • format (Boolean) (defaults to: true) —

    false: the resource’s routes match no .:format extension (the block’s routes keep their own)

Yield Parameters:

Returns:

  • (nil)


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).

Examples:

resources :articles do |articles|
  articles.resources :comments, only: [:create, :destroy]
  articles.member { |m| m.get "preview" }        # GET /articles/:id/preview, preview_article_path
  articles.collection { |c| c.get "search" }     # GET /articles/search, search_articles_path
end

Parameters:

  • name (Symbol) —

    the plural (:articles)

  • only (Array<Symbol>, nil) (defaults to: nil) —

    draw only these actions

  • except (Array<Symbol>, nil) (defaults to: nil) —

    draw all but these

  • controller (String) (defaults to: "") —

    the controller ("metrics"), under the enclosing namespace’s module; default the plural

  • param (Symbol) (defaults to: :id) —

    the member segment’s name (:key)

  • format (Boolean) (defaults to: true) —

    false: the seven routes match no .:format extension (the block’s routes keep their own)

Yield Parameters:

  • mapper (Mapper) —

    the mapper, to call with an explicit receiver inside the block (articles.resources): Spinel gives a nested block no implicit self

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    for a param: that is not a lowercase name



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)
    message = "param: must be a lowercase name (got #{key.inspect})"
    raise ArgumentError, message
  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).

Parameters:

  • to (String) —

    "controller#action"

  • format (Boolean) (defaults to: true) —

    false: match no .:format extension

Returns:

  • (nil)


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").

Examples:

scope "/v1", as: "v1" do |v|
  v.get "/about", to: "pages#about"   # GET /v1/about, v1_about_path
end

Parameters:

  • path (String) (defaults to: "") —

    the path prefix ("dashboard" or "/dashboard")

  • module (String) (defaults to: "") —

    the controller module ("admin")

  • as (String) (defaults to: "") —

    the helper-name prefix ("admin")

Yield Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    inside resources or resource



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