Class: Cybertrain::Controller
- Inherits:
-
Object
- Object
- Cybertrain::Controller
- Defined in:
- cybertrain/streams.rb,
cybertrain/controller.rb,
cybertrain/rate_limit.rb
Overview
Base class of every application controller, through the app’s
ApplicationController. One instance handles one request: the router
builds it, runs the before callbacks, the action, the implicit render and
the after callbacks.
class ArticlesController < ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy]
def index
@articles = Article.all.to_a
end
def new_action # GET /articles/new: a method named `new` would shadow ArticlesController.new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
flash[:notice] = "Article was successfully created."
redirect_to article_path(@article), status: :see_other
else
render :new, status: :unprocessable_entity
end
end
private
def set_article
@article = Article.find(params[:id])
end
def article_params
params.require(:article).permit(:title, :body)
end
end
Rules that differ from Rails, all because Spinel compiles ahead of time
with no send or instance_exec:
- Actions are public methods; the
newaction isdef new_action(its view is stillnew.html.erb, its action name"new"). - Templates see the instance variables assigned (
@x = ...) in the controller’s file or its parents’ files, found byspin run gen; re-run it after adding one (cybertrain serverdoes). - A block callback takes the controller as its argument
(
before_action { |c| ... }), so it can call public methods only. skip_before_action :name, only: [...]leaves out a named callback a parent declared; there is noskip_after_action.renderandredirect_todo not end the action, and a second one replaces the first;returnafter them when more code follows.- Every controller also has the route helpers (
article_path(...), see Gen::UrlHelpers).
Implementation: the router calls
process(:show) { |c| c.show }, so the action name and
the action body both arrive as literals (no send).
Callback and rescue declarations are runtime data keyed by class name; symbol callbacks are dispatched through run_callback(name), which gen/controllers.rb overrides in each controller with a case table.
Constant Summary collapse
- STATUS_SYMBOLS =
The Symbols
status:accepts in #render, #head and #redirect_to: the Rails names of the codes inResponse::STATUS_TEXT, one Symbol per code there (Rack 3’s names,:content_too_largeand:unprocessable_contentamong them), plus the older names:payload_too_large,:request_entity_too_large,:unprocessable_entity,:request_uri_too_longand:requested_range_not_satisfiable. Any other status must be given as an Integer. { continue: 100, switching_protocols: 101, processing: 102, early_hints: 103, ok: 200, created: 201, accepted: 202, non_authoritative_information: 203, no_content: 204, reset_content: 205, partial_content: 206, multi_status: 207, already_reported: 208, im_used: 226, multiple_choices: 300, moved_permanently: 301, found: 302, see_other: 303, not_modified: 304, use_proxy: 305, temporary_redirect: 307, permanent_redirect: 308, bad_request: 400, unauthorized: 401, payment_required: 402, forbidden: 403, not_found: 404, method_not_allowed: 405, not_acceptable: 406, proxy_authentication_required: 407, request_timeout: 408, conflict: 409, gone: 410, length_required: 411, precondition_failed: 412, content_too_large: 413, uri_too_long: 414, unsupported_media_type: 415, range_not_satisfiable: 416, expectation_failed: 417, misdirected_request: 421, unprocessable_content: 422, locked: 423, failed_dependency: 424, too_early: 425, upgrade_required: 426, precondition_required: 428, too_many_requests: 429, request_header_fields_too_large: 431, unavailable_for_legal_reasons: 451, internal_server_error: 500, not_implemented: 501, bad_gateway: 502, service_unavailable: 503, gateway_timeout: 504, http_version_not_supported: 505, variant_also_negotiates: 506, insufficient_storage: 507, loop_detected: 508, not_extended: 510, network_authentication_required: 511, payload_too_large: 413, request_entity_too_large: 413, unprocessable_entity: 422, request_uri_too_long: 414, requested_range_not_satisfiable: 416 }
Instance Attribute Summary collapse
-
#action_name ⇒ String
readonly
The action being run, by its route name:
"show", and"new"fornew_action. -
#params ⇒ Params
readonly
The request parameters: the query string, a urlencoded form body and the route’s
:id-style segments (in that order, later ones winning). -
#request ⇒ Request
readonly
The request: method, path, headers, raw body.
-
#rescued_exception ⇒ StandardError?
readonly
The exception a Controller.rescue_from
with:method is handling. -
#response ⇒ Response
readonly
The response being built.
Class Method Summary collapse
-
.after_action(name = nil, only: [], except: []) {|controller| ... } ⇒ nil
Runs a method or a block after the action and its implicit render, in the same order as Controller.before_action (not reversed).
-
.allow_unauthenticated_access(only: [], except: []) ⇒ nil
Opens actions to visitors who are not signed in, as Rails 8’s authentication concern does:
skip_before_action :require_authenticationfor every action, or foronly:/except:some. -
.before_action(name = nil, only: [], except: []) {|controller| ... } ⇒ nil
Runs a method or a block before the action.
-
.concern_insert_at(callbacks_index, rescues_index) ⇒ nil
Written by gen/concerns.rb (
spin run gen) around theincludedbody of a concern it splices into this class: until Controller.concern_insert_done, the callbacks andrescue_fromhandlers the body declares go to these positions of the class’s own lists (the count of declarations above theincludeline), not to the end, so they run where theincludewas written. -
.concern_insert_done ⇒ nil
Ends a Controller.concern_insert_at splice: declarations append again.
-
.content_security_policy {|policy| ... } ⇒ nil
This controller’s own Content Security Policy (spec C-5): a copy of the nearest ancestor’s, or of the application’s (Config#content_security_policy, declared in config/app.rb, which loads first), yielded at once to the block and kept for this class and its subclasses.
-
.helper_method(*names) ⇒ nil
Makes controller methods callable from this controller’s templates (spec 4.3).
-
.layout(name = nil, only: [], except: []) ⇒ nil
Names this controller’s layout.
-
.rate_limit(to:, within:, only: [], except: [], by: :client_ip, with: nil, if: nil, unless: nil, name: "", store: :cache, redirect_to: "", alert: "") ⇒ nil
Limits how often one client may call some actions: at most
torequests perwithinseconds for each client, counted before the action runs (a before callback, in declaration order with the others). -
.rescue_from(klass, with: nil) {|controller, exception| ... } ⇒ nil
Handles an exception raised by a callback, the action or its render:
rescue_from NotFound, with: :not_foundorrescue_from(NotFound) { |c, e| c.head :not_found }. -
.skip_before_action(name, only: [], except: []) ⇒ nil
Leaves out a named before callback a parent class (or this one) declared, for every action or for
only:/except:some.
Instance Method Summary collapse
-
#controller_layout(action) ⇒ String
The layout an action’s HTML renders in:
"layouts/application"(the configured Views.layout_name) here, and in a controller withlayoutlines the one they choose for the action. -
#controller_path ⇒ String
“posts” for PostsController: the directory under
app/views/its templates come from. -
#cookies ⇒ CookieJar
The request’s cookies: plain,
permanent,signedandencrypted(see CookieJar). -
#expires_in(seconds, public: false) ⇒ nil
Lets the browser reuse the response for
secondswithout asking:Cache-Control: max-age=<seconds>, private(publicwithpublic: true). -
#flash ⇒ Flash
Messages for the next request (
flash[:notice] = "Saved."before a redirect) or, throughflash.now, for this one. -
#fresh_when(etag: DEFAULT_VALIDATOR, last_modified: DEFAULT_VALIDATOR, public: false) ⇒ nil
Sets the response’s validators and answers
304 Not Modified(no body) when the request’sIf-None-Match/If-Modified-Sinceshow the client already has the current version; otherwise the action goes on and renders as usual. -
#head(status = DEFAULT_STATUS) ⇒ nil
Answers with a status and an empty body.
-
#local_path?(text) ⇒ Boolean
Whether
textis a path on this site that is safe to redirect to: it starts with/but not//or/\(which browsers read as another host), holds printable ASCII only (no space, control character, backslash or byte above 126: browsers strip or reinterpret those; a path the browser sent is percent-encoded already) and is at most MAX_LOCAL_PATH_BYTES bytes. -
#performed? ⇒ Boolean
True once this request has been rendered, redirected or answered with #head.
-
#redirect_to(location, status: DEFAULT_REDIRECT_STATUS) ⇒ nil
Answers with a redirect (302 by default) to a URL String: build it with a route helper.
-
#render(template = nil, plain: nil, html: nil, json: nil, status: DEFAULT_STATUS, content_type: nil, partial: nil, locals: {}, layout: DEFAULT_LAYOUT, turbo_stream: nil) ⇒ nil
Renders the response from a template, text, HTML or JSON: exactly one of template, plain:, html:, json: or partial:.
-
#respond_to {|format| ... } ⇒ nil
Answers by the request’s format (Request#format): the block gets a FormatCollector, and the first of its declarations that matches the format runs its block at once (the blocks see the action’s instance variables and call #render as the action would).
-
#safe_redirect_path(text, fallback) ⇒ String
textwhen it is a #local_path?, otherwisefallback: the destination to give #redirect_to for a path that came from the request. -
#send_blob(data, filename:, content_type:) ⇒ nil
Serves stored bytes that came from a user (an upload), safely.
-
#send_data(data, filename: "", type: "application/octet-stream", disposition: "attachment", status: DEFAULT_STATUS) ⇒ nil
Sends
dataas a download (Rails’send_data): the body isdata, the Content-Type istype, and the Content-Disposition isattachment(orinline) with the file name in both the quoted fallback form and RFC 5987’sfilename*(UploadedFile.content_disposition_utf8), so a name with accents or a quote survives. -
#session ⇒ Session
This visitor’s session, kept in an encrypted cookie (AES-256-GCM).
-
#stale?(etag: DEFAULT_VALIDATOR, last_modified: DEFAULT_VALIDATOR, public: false) ⇒ Boolean
#fresh_when, for an action that renders only when the client’s copy is out of date: sets the validators, answers
304and returns false when the request is fresh, returns true otherwise. -
#stream(content_type: "text/event-stream", status: DEFAULT_STATUS) {|out| ... } ⇒ nil
Answers with a streaming response (Rails’ ActionController::Live, without the module): the block runs after the action has returned, on the connection’s thread, once the head is sent, and receives the Sink to write to.
-
#t(key, options = {}) ⇒ String
I18n.t from an action: a key starting with “.” is looked up under the controller path and the action, as Rails’ controller
tdoes (t(".created")in Admin::PostsController#create readsadmin.posts.create.created). -
#translate(key, options = {}) ⇒ String
The same as #t.
-
#turbo_stream ⇒ TurboStreams
The Turbo Stream builder of an action (turbo-rails’
turbo_stream): replace, update, append, prepend, before and after (a target and one ofpartial:withlocals:, orhtml:) and remove (a target), each a<turbo-stream>element forrender turbo_stream:.
Instance Attribute Details
#action_name ⇒ String (readonly)
The action being run, by its route name: "show", and "new" for
new_action.
533 534 535 |
# File 'cybertrain/controller.rb', line 533 def action_name @action_name end |
#params ⇒ Params (readonly)
The request parameters: the query string, a urlencoded form body and
the route’s :id-style segments (in that order, later ones winning).
527 528 529 |
# File 'cybertrain/controller.rb', line 527 def params @params end |
#request ⇒ Request (readonly)
The request: method, path, headers, raw body.
510 511 512 |
# File 'cybertrain/controller.rb', line 510 def request @request end |
#rescued_exception ⇒ StandardError? (readonly)
The exception a rescue_from with: method is handling.
538 539 540 |
# File 'cybertrain/controller.rb', line 538 def rescued_exception @rescued_exception end |
#response ⇒ Response (readonly)
The response being built. #render, #redirect_to and #head fill it; set headers and cookies on it directly.
518 519 520 |
# File 'cybertrain/controller.rb', line 518 def response @response end |
Class Method Details
.after_action(name = nil, only: [], except: []) {|controller| ... } ⇒ nil
Runs a method or a block after the action and its implicit render, in the same order as before_action (not reversed). Skipped when a before callback halted or anything raised.
195 196 197 |
# File 'cybertrain/controller.rb', line 195 def self.after_action(name = nil, only: [], except: [], &block) add_callback(Callback.new(:after, name, block, only, except, -1)) end |
.allow_unauthenticated_access(only: [], except: []) ⇒ nil
Opens actions to visitors who are not signed in, as Rails 8’s
authentication concern does: skip_before_action
:require_authentication for every action, or for only: / except:
some. cybertrain generate authentication writes the
require_authentication callback this skips.
class PasswordsController < ApplicationController
allow_unauthenticated_access only: [:new, :create]
(An application whose ApplicationController defines its own
self.allow_unauthenticated_access, as 0.4’s generator wrote it,
keeps using that one.)
364 365 366 |
# File 'cybertrain/controller.rb', line 364 def self.allow_unauthenticated_access(only: [], except: []) skip_before_action(:require_authentication, only: only, except: except) end |
.before_action(name = nil, only: [], except: []) {|controller| ... } ⇒ nil
Runs a method or a block before the action. The chain runs the parent classes’ callbacks first, then each class’s in declaration order, and stops at the first callback that renders, redirects or calls #head: the action, the implicit render and the after callbacks are then skipped.
One method name per call. The method is called without a receiver, so
it may be private; it must be named on the same line as
before_action for spin run gen to find it.
180 181 182 |
# File 'cybertrain/controller.rb', line 180 def self.before_action(name = nil, only: [], except: [], &block) add_callback(Callback.new(:before, name, block, only, except, -1)) end |
.concern_insert_at(callbacks_index, rescues_index) ⇒ nil
Written by gen/concerns.rb (spin run gen) around the included
body of a concern it splices into this class: until
concern_insert_done, the callbacks and rescue_from handlers the
body declares go to these positions of the class’s own lists (the
count of declarations above the include line), not to the end, so
they run where the include was written. Not for application code.
222 223 224 225 226 |
# File 'cybertrain/controller.rb', line 222 def self.concern_insert_at(callbacks_index, rescues_index) CONCERN_CALLBACK_AT[self.name] = callbacks_index CONCERN_RESCUE_AT[self.name] = rescues_index nil end |
.concern_insert_done ⇒ nil
Ends a concern_insert_at splice: declarations append again.
231 232 233 234 235 |
# File 'cybertrain/controller.rb', line 231 def self.concern_insert_done CONCERN_CALLBACK_AT.delete(self.name) CONCERN_RESCUE_AT.delete(self.name) nil end |
.content_security_policy {|policy| ... } ⇒ nil
This controller’s own Content Security Policy (spec C-5): a copy of
the nearest ancestor’s, or of the application’s
(Config#content_security_policy, declared in config/app.rb, which
loads first), yielded at once to the block and kept for this class
and its subclasses. The block runs here, once; nothing stores it
(NOTES rule 88). Its actions’ responses carry this policy instead of
the application’s. The copy is taken when the class body runs, so
config/app.rb must load before the controllers (bin/
282 283 284 285 286 287 288 289 290 |
# File 'cybertrain/controller.rb', line 282 def self.content_security_policy(&block) inherited = Controller.policy_for(self) inherited = Cybertrain.config.content_security_policy_value if inherited.nil? policy = inherited.nil? ? ContentSecurityPolicy.new : inherited.dup_policy block.call(policy) CSP_POLICIES[self.name] = policy ContentSecurityPolicy.controller_policy_declared! nil end |
.helper_method(*names) ⇒ nil
Makes controller methods callable from this controller’s templates
(spec 4.3). A declaration only: spin run gen reads the names.
244 245 246 |
# File 'cybertrain/controller.rb', line 244 def self.helper_method(*names) nil end |
.layout(name = nil, only: [], except: []) ⇒ nil
Names this controller’s layout. A declaration only: spin run gen
reads it.
259 260 261 |
# File 'cybertrain/controller.rb', line 259 def self.layout(name = nil, only: [], except: []) nil end |
.rate_limit(to:, within:, only: [], except: [], by: :client_ip, with: nil, if: nil, unless: nil, name: "", store: :cache, redirect_to: "", alert: "") ⇒ nil
Limits how often one client may call some actions: at most to
requests per within seconds for each client, counted before the
action runs (a before callback, in declaration order with the
others). An exhausted client gets a 429 with the body “Too Many
Requests” and a Retry-After header (the seconds until its window
closes), or, with redirect_to:, a 303 to that path with alert: in
the flash, or what the with: method answers. The action does not
run.
The counts are shared through the cache (store: :cache, the
default; see RateLimit): every process of the application counts
together, in fixed windows aligned to the epoch. store: :memory
keeps them in this process instead.
A count is kept per declaration (its name:), per controller (a
limit declared in a parent counts each subclass apart, as Rails’
does) and per client: Request#client_ip by default, so behind a
proxy on the same host set Config#trusted_proxy, or every visitor
shares the proxy’s address; by: :remote_addr counts the
connection’s peer whatever the configuration; by: :user_key the
String the controller’s user_key method answers (an empty one
raises ArgumentError rather than count every client in one bucket).
if: :m applies the limit only when the method m answers true,
unless: :m only when it answers false; a request it does not apply
to is not counted. The methods named by by:, with:, if: and
unless: are called through the tables spin run gen writes
(#rate_limit_key, #rate_limit_condition?, #run_callback).
Differences from Rails: within: is a number of seconds (3 * 60;
there is no 3.minutes), only:/except: take Arrays, by:,
with:, if: and unless: take a method’s name rather than a
block, store: is :cache or :memory rather than a cache store,
and each limit of a controller (its parents’ included) needs its own
name:.
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 |
# File 'cybertrain/rate_limit.rb', line 381 def self.rate_limit(to:, within:, only: [], except: [], by: :client_ip, with: nil, if: nil, unless: nil, name: "", store: :cache, redirect_to: "", alert: "") raise ArgumentError, "rate_limit needs to: of at least 1 (got #{to})" if to < 1 raise ArgumentError, "rate_limit needs within: of at least 1 second (got #{within})" if within < 1 memory_store = false case store when :cache then memory_store = false when :memory then memory_store = true else msg = "rate_limit store: must be :cache or :memory (got #{store.inspect})" raise ArgumentError, msg end if name.include?(":") msg = "rate_limit name: may not contain \":\" (got #{name.inspect})" raise ArgumentError, msg end if rate_limit_named?(self, name) msg = "rate_limit name: #{name.inspect} is already taken in #{self.name}; give each limit of a controller its own name:" raise ArgumentError, msg end by_remote_addr = false by_method = nil case by when :client_ip then by_remote_addr = false when :remote_addr then by_remote_addr = true else by_method = by end # `if` and `unless` are keywords: their values are read by name. if_method = binding.local_variable_get(:if) unless_method = binding.local_variable_get(:unless) limit = RateLimit.new(to, within, by_remote_addr, redirect_to, alert, by_method, with, if_method, unless_method, name, memory_store) id = RateLimit.register(limit) add_callback(Callback.new(:before, nil, nil, only, except, id)) end |
.rescue_from(klass, with: nil) {|controller, exception| ... } ⇒ nil
Handles an exception raised by a callback, the action or its render:
rescue_from NotFound, with: :not_found or
rescue_from(NotFound) { |c, e| c.head :not_found }.
Unlike Rails, the class must match exactly (a subclass does not), and
the first handler found wins, looking in this class before its parents.
A with: method reads the exception from #rescued_exception; keep
with: on the same line as rescue_from. A handler that renders
nothing leaves an empty 200.
Unhandled, a Params::ParameterMissing or malformed query answers 400 and anything else 500 (a RecordNotFound too: the generated ApplicationController rescues it to a 404).
431 432 433 434 435 436 437 438 439 440 441 442 443 |
# File 'cybertrain/controller.rb', line 431 def self.rescue_from(klass, with: nil, &block) list = (RESCUES[self.name] ||= []) handler = RescueHandler.new(klass.name, with, block) if CONCERN_RESCUE_AT.key?(self.name) at = CONCERN_RESCUE_AT[self.name] at = list.size if at > list.size list.insert(at, handler) CONCERN_RESCUE_AT[self.name] = at + 1 else list << handler end nil end |
.skip_before_action(name, only: [], except: []) ⇒ nil
Leaves out a named before callback a parent class (or this one)
declared, for every action or for only: / except: some. The
usual shape is an ApplicationController that requires a signed-in
user everywhere and a controller that opens its sign-in actions:
class SessionsController < ApplicationController
skip_before_action :require_authentication, only: [:new, :create]
A skip declared in a class applies to it and its subclasses. Block
callbacks have no name and cannot be skipped. allow_unauthenticated_access
is this for :require_authentication.
343 344 345 346 |
# File 'cybertrain/controller.rb', line 343 def self.skip_before_action(name, only: [], except: []) (SKIPS[self.name] ||= []) << Callback.new(:skip, name, nil, only, except, -1) nil end |
Instance Method Details
#controller_layout(action) ⇒ String
The layout an action’s HTML renders in: "layouts/application" (the
configured Views.layout_name) here, and in a controller with
layout lines the one they choose for the action. gen/controllers.rb
writes the override from them, in order, the first that applies
winning, else super:
layout "admin", only: [:index] # "layouts/admin" for index
layout false # "" (no layout)
layout :choose_layout # its value: a name, false, or nil (inherited)
A concern’s included block may declare one too; it counts at its
include line.
751 752 753 |
# File 'cybertrain/controller.rb', line 751 def controller_layout(action) Views.layout_name end |
#controller_path ⇒ String
“posts” for PostsController: the directory under app/views/ its
templates come from.
724 725 726 727 728 729 730 731 732 733 734 |
# File 'cybertrain/controller.rb', line 724 def controller_path known = @controller_path return known unless known.empty? # Asked for several times in a render (the environment, the template's # path), each an underscore of the class name: remembered. name = Inflector.underscore(self.class.name) path = name.end_with?("_controller") ? name[0, name.length - 11] : name @controller_path = path path end |
#cookies ⇒ CookieJar
The request’s cookies: plain, permanent, signed and encrypted
(see Cybertrain::CookieJar). SessionStore builds the jar; without it in the
stack, a jar over the request’s Cookie header is built on first use,
whose signed and encrypted raise (there is no key).
568 569 570 571 572 573 574 575 576 |
# File 'cybertrain/controller.rb', line 568 def jar = @ctx. return jar unless jar.nil? parsed = Cookies.parse(request.) built = CookieJar.new(parsed, response, secure: Cybertrain.config.) @ctx. = built built end |
#expires_in(seconds, public: false) ⇒ nil
Lets the browser reuse the response for seconds without asking:
Cache-Control: max-age=<seconds>, private (public with
public: true). Rails’ expires_in; a later #fresh_when keeps this
header.
1255 1256 1257 |
# File 'cybertrain/controller.rb', line 1255 def expires_in(seconds, public: false) HttpCache.lifetime(@response, seconds, public) end |
#flash ⇒ Flash
Messages for the next request (flash[:notice] = "Saved." before a
redirect) or, through flash.now, for this one.
554 555 556 |
# File 'cybertrain/controller.rb', line 554 def flash @ctx.flash end |
#fresh_when(etag: DEFAULT_VALIDATOR, last_modified: DEFAULT_VALIDATOR, public: false) ⇒ nil
Sets the response’s validators and answers 304 Not Modified (no
body) when the request’s If-None-Match / If-Modified-Since show
the client already has the current version; otherwise the action goes
on and renders as usual. Rails’ fresh_when.
etag: is a String or a record. A String is taken as it is; a record
is keyed by "<table>/<to_param>-<updated_at epoch>", so it changes
when the record is saved. The key is hashed together with the
request’s format (Request#format), so the HTML and the JSON or
Turbo Stream of one URL never share an ETag; with whether the request
may be answered in HTML instead of its own format (an Accept of
application/json, text/html, see #respond_to), so the ETag of a
page sent to such a request is never the ETag of a request for JSON
alone, which gets JSON or 406; and with
Assets.build_digest, so a deploy that changes the assets (or, in a
cybertrain build binary, the views) changes every ETag. The key
names the record, not the visitor: a page that differs per user
needs the user in its key, as in Rails:
etag: "posts/#{@post.id}-#{@post.updated_at.to_i}-#{current_user.id}". The header is a weak ETag,
W/"<first 32 hex digits of the SHA-256>"; If-None-Match matches it
in a list, in weak or strong form; If-None-Match: * matches whatever
was validated, also a response with only Last-Modified (RFC 9110
13.1.2); any other etag: is an
ArgumentError. last_modified: is a Time, sent as Last-Modified; an
unparseable If-Modified-Since is ignored. When the request sends an
If-None-Match, it alone decides and If-Modified-Since is ignored
(RFC 9110 13.1.3). Only GET and HEAD are answered 304.
Cache-Control is max-age=0, private, must-revalidate (public when
public: true) unless #expires_in already set one. Do not make a
page public when it carries a CSP nonce (content_security_policy
with nonces, javascript_importmap_tags): a shared cache hands the
same page, and so the same nonce, to every visitor, and a nonce
everyone knows protects nothing.
1216 1217 1218 1219 1220 |
# File 'cybertrain/controller.rb', line 1216 def fresh_when(etag: DEFAULT_VALIDATOR, last_modified: DEFAULT_VALIDATOR, public: false) HttpCache.set_validators(@request, @response, etag, last_modified, public, Rendering.accepts_html?(@request)) head :not_modified if HttpCache.validators_fresh?(@request, @response) nil end |
#head(status = DEFAULT_STATUS) ⇒ nil
Answers with a status and an empty body.
status defaults to :ok only so that Spinel boxes the parameter (see DEFAULT_STATUS); callers are expected to pass one.
1053 1054 1055 1056 1057 1058 |
# File 'cybertrain/controller.rb', line 1053 def head(status = DEFAULT_STATUS) @response.status = Controller.status_code(status) @response.body = "" @response.performed! nil end |
#local_path?(text) ⇒ Boolean
Whether text is a path on this site that is safe to redirect to: it
starts with / but not // or /\ (which browsers read as another
host), holds printable ASCII only (no space, control character,
backslash or byte above 126: browsers strip or reinterpret those; a
path the browser sent is percent-encoded already) and is at most
MAX_LOCAL_PATH_BYTES bytes. Use it on any destination that came
from the request (a return_to parameter, a remembered page).
1004 1005 1006 |
# File 'cybertrain/controller.rb', line 1004 def local_path?(text) Controller.local_path_text?(text) end |
#performed? ⇒ Boolean
Returns true once this request has been rendered, redirected or answered with #head.
1262 1263 1264 |
# File 'cybertrain/controller.rb', line 1262 def performed? @response.performed? end |
#redirect_to(location, status: DEFAULT_REDIRECT_STATUS) ⇒ nil
Answers with a redirect (302 by default) to a URL String: build it with
a route helper. After a form submission use status: :see_other
(303), as the scaffold does, so the browser follows with a GET. It
does not end the action. To show a message on the next page, set
#flash first.
983 984 985 986 |
# File 'cybertrain/controller.rb', line 983 def redirect_to(location, status: DEFAULT_REDIRECT_STATUS) @response.redirect(location, Controller.status_code(status)) nil end |
#render(template = nil, plain: nil, html: nil, json: nil, status: DEFAULT_STATUS, content_type: nil, partial: nil, locals: {}, layout: DEFAULT_LAYOUT, turbo_stream: nil) ⇒ nil
Renders the response from a template, text, HTML or JSON: exactly one of template, plain:, html:, json: or partial:.
An action that renders nothing renders its own template
(app/views/<controller_path>/<action>.html.erb) in the layout, or
for another request format <action>.<format>.erb without one
(create.turbo_stream.erb), else answers 406 Not Acceptable; see
#respond_to to answer each format differently.
template:app/views/<controller_path>/<template>.html.erb, always this controller’s directory, inside the controller’s layout (#controller_layout:app/views/layouts/application.html.erbunless alayoutline chooses another), when it exists.layout: "admin"(or"layouts/admin") usesapp/views/layouts/admin.html.erbinstead, and raises MissingTemplate when that layout does not exist;layout: falsenone. Inside a #respond_to declaration for another format (format.json { render :show }) it is<template>.<format>.erb(show.json.erb), never in a layout.plain:the String astext/plain.html:astext/html; a plain String is escaped, a SafeString is sent as it is.json:asapplication/json; a String is sent as it is (taken to be JSON already), anything else goes throughJSON.generate. For a record, pass Model#as_json or Model#to_json.partial:_<name>.html.erb("form"in this controller’s directory,"comments/comment"in another), never in a layout.turbo_stream:a<turbo-stream>element (#turbo_stream builds them) or an Array of them, joined, astext/vnd.turbo-stream.html, never in a layout. A plain String is refused: build the elements with #turbo_stream.
It does not end the action: a later render or redirect_to
replaces it.
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 |
# File 'cybertrain/controller.rb', line 904 def render(template = nil, plain: nil, html: nil, json: nil, status: DEFAULT_STATUS, content_type: nil, partial: nil, locals: {}, layout: DEFAULT_LAYOUT, turbo_stream: nil) given = 0 given += 1 unless template.nil? given += 1 unless plain.nil? given += 1 unless html.nil? given += 1 unless json.nil? given += 1 unless partial.nil? given += 1 unless turbo_stream.nil? raise ArgumentError, "render needs exactly one of template, plain:, html:, json:, partial:, turbo_stream:" if given != 1 @response.status = Controller.status_code(status) if !turbo_stream.nil? @response.body = Rendering.turbo_stream_text(turbo_stream) @response.content_type = Request.mime_type(:turbo_stream) elsif !plain.nil? @response.body = plain @response.content_type = "text/plain; charset=utf-8" elsif !html.nil? @response.body = Html.out(html) @response.content_type = HTML_CONTENT_TYPE elsif !json.nil? @response.body = Rendering.json_text(json) @response.content_type = "application/json; charset=utf-8" elsif !partial.nil? render_partial(partial.to_s, locals) else chosen = "" if layout == true chosen = controller_layout(@action_name) elsif layout != false chosen = Rendering.layout_named(layout.to_s) end wanted = @respond_format == :none ? :html : @respond_format render_template(template.to_s, locals, layout: chosen, format: wanted) end @response.content_type = content_type unless content_type.nil? @response.performed! nil end |
#respond_to {|format| ... } ⇒ nil
Answers by the request’s format (Request#format): the block gets a
FormatCollector, and the first of its declarations that matches the
format runs its block at once (the blocks see the action’s instance
variables and call #render as the action would). A matching
declaration without a block renders the action’s template for that
format (show.html.erb in the layout, show.turbo_stream.erb
without one). When no declaration matches, the answer is 406 Not
Acceptable (text/plain, body Not Acceptable).
Turbo submits a form asking for text/vnd.turbo-stream.html,
text/html: its format is :turbo_stream, and an action with no
format.turbo_stream answers through its format.html declaration,
as in Rails (a .turbo_stream extension asks for that format only).
The same holds for any format that came from an Accept header that
also lists text/html or */* (axios sends application/json,
text/plain, */*): with no declaration for it, format.html answers.
A q=0 refuses its type: application/json, text/html;q=0 gets no
HTML and so the 406, with or without */* beside it.
Inside the matching declaration’s block, render :x renders the
template of the format that matched (x.json.erb in format.json),
and when the block renders nothing the implicit render does too.
That HTML fallback runs the whole block a second time, now for
:html: no declaration’s block ran in the first pass, but any other
statement in the block (outside a format.x) runs twice, so keep
the block to declarations. (Rails replays stored declarations; this
framework stores no blocks.)
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 |
# File 'cybertrain/controller.rb', line 823 def respond_to(&block) # Set before the block runs: a matching declaration's block runs # inside block.call, and its `render :x` reads it. @respond_format = @request.format collector = FormatCollector.new(@request.format) block.call(collector) if collector.matched_format == :none && Rendering.accepts_html?(@request) # Nothing ran in the first pass, so running the block again for # :html runs at most one declaration's block. @respond_format = :html collector = FormatCollector.new(:html) block.call(collector) end matched = collector.matched_format @respond_format = matched if matched == :none head_not_acceptable elsif collector.matched_without_block? render_template(@action_name, format: matched) end nil end |
#safe_redirect_path(text, fallback) ⇒ String
text when it is a #local_path?, otherwise fallback: the
destination to give #redirect_to for a path that came from the
request.
1017 1018 1019 1020 1021 |
# File 'cybertrain/controller.rb', line 1017 def safe_redirect_path(text, fallback) return fallback unless Controller.local_path_text?(text) text.to_s end |
#send_blob(data, filename:, content_type:) ⇒ nil
Serves stored bytes that came from a user (an upload), safely. This is
the only supported way to send an upload back: never put uploads under
public/, because Static serves them with whatever type their
extension implies.
The bytes are untrusted, so the response never lets a browser run them:
- only PNG, JPEG, GIF and WebP (UploadedFile::INLINE_SAFE_TYPES) are
sent
inlineunder their own type; every other type (SVG and HTML included) is anattachmenttypedapplication/octet-stream; filenameis sanitized again (UploadedFile.sanitize_filename, in case the stored value was tampered with) and the Content-Disposition header is ASCII only;X-Content-Type-Options: nosniff,Content-Security-Policy: default-src 'none'; sandboxandCache-Control: private, max-age=3600are always set. (nosniff andX-Frame-Options: SAMEORIGINare also the defaults of every response, see Response#to_http; the header set here is the one sent, not a second copy.)
HEAD works as for any action: the Server leaves the body out.
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 |
# File 'cybertrain/controller.rb', line 1126 def send_blob(data, filename:, content_type:) inline = UploadedFile.inline_safe?(content_type) r = @response r.status = 200 r.content_type = inline ? content_type : "application/octet-stream" r.set_header("Content-Disposition", UploadedFile.content_disposition(inline ? "inline" : "attachment", UploadedFile.sanitize_filename(filename))) r.set_header("X-Content-Type-Options", "nosniff") r.set_header("Content-Security-Policy", "default-src 'none'; sandbox") r.set_header("Cache-Control", "private, max-age=3600") r.body = data r.performed! nil end |
#send_data(data, filename: "", type: "application/octet-stream", disposition: "attachment", status: DEFAULT_STATUS) ⇒ nil
Sends data as a download (Rails’ send_data): the body is data,
the Content-Type is type, and the Content-Disposition is
attachment (or inline) with the file name in both the quoted
fallback form and RFC 5987’s filename*
(UploadedFile.content_disposition_utf8), so a name with accents or a
quote survives. With no filename: the header is the bare disposition.
Marks the response performed.
The bytes are served under whatever type says, so this is for data
the application made (a CSV export, a generated PDF); bytes a user
uploaded go through #send_blob, which never lets a browser run them.
1162 1163 1164 1165 1166 1167 1168 1169 1170 |
# File 'cybertrain/controller.rb', line 1162 def send_data(data, filename: "", type: "application/octet-stream", disposition: "attachment", status: DEFAULT_STATUS) r = @response r.status = Controller.status_code(status) r.content_type = type r.set_header("Content-Disposition", UploadedFile.content_disposition_utf8(disposition, filename)) r.body = data r.performed! nil end |
#session ⇒ Session
This visitor’s session, kept in an encrypted cookie (AES-256-GCM).
The session and flash installed by SessionStore (nil when the middleware is not in the stack, e.g. in bare unit tests).
546 547 548 |
# File 'cybertrain/controller.rb', line 546 def session @ctx.session end |
#stale?(etag: DEFAULT_VALIDATOR, last_modified: DEFAULT_VALIDATOR, public: false) ⇒ Boolean
#fresh_when, for an action that renders only when the client’s copy
is out of date: sets the validators, answers 304 and returns false
when the request is fresh, returns true otherwise. Rails’ stale?.
1235 1236 1237 1238 1239 1240 1241 |
# File 'cybertrain/controller.rb', line 1235 def stale?(etag: DEFAULT_VALIDATOR, last_modified: DEFAULT_VALIDATOR, public: false) HttpCache.set_validators(@request, @response, etag, last_modified, public, Rendering.accepts_html?(@request)) return true unless HttpCache.validators_fresh?(@request, @response) head :not_modified false end |
#stream(content_type: "text/event-stream", status: DEFAULT_STATUS) {|out| ... } ⇒ nil
Answers with a streaming response (Rails’ ActionController::Live, without the module): the block runs after the action has returned, on the connection’s thread, once the head is sent, and receives the Sink to write to. The connection closes when the block returns, or when the client goes away (Sink#closed?: end the loop then). The block must not touch the session, flash or response any more: they were sent with the head. Marks the response performed, like #render.
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 |
# File 'cybertrain/controller.rb', line 1081 def stream(content_type: "text/event-stream", status: DEFAULT_STATUS, &block) r = @response r.status = Controller.status_code(status) r.content_type = content_type r.set_header("Cache-Control", "no-store") # Stored and called later from BlockWriter#write_body, a plain method # (spikes/NOTES.md rules 2, 69). r.body_writer = BlockWriter.new(block) r.performed! nil end |
#t(key, options = {}) ⇒ String
I18n.t from an action: a key starting with “.” is looked up under
the controller path and the action, as Rails’ controller t does
(t(".created") in Admin::PostsController#create reads
admin.posts.create.created). A key ending in _html or .html
has its interpolated values escaped; the answer is a String all the
same (wrap it in a SafeString to render it as HTML).
705 706 707 708 709 710 711 |
# File 'cybertrain/controller.rb', line 705 def t(key, = {}) k = key.to_s k = "#{controller_path.tr("/", ".")}.#{@action_name}#{k}" if k.start_with?(".") return I18n.t(k, Template::Helpers.escaped_interpolations()) if I18n.html_key?(k) I18n.t(k, ) end |
#translate(key, options = {}) ⇒ String
The same as #t.
718 |
# File 'cybertrain/controller.rb', line 718 def translate(key, = {}) = t(key, ) |
#turbo_stream ⇒ TurboStreams
The Turbo Stream builder of an action (turbo-rails’ turbo_stream):
replace, update, append, prepend, before and after (a target and one
of partial: with locals:, or html:) and remove (a target), each
a <turbo-stream> element for render turbo_stream:.
44 45 46 |
# File 'cybertrain/streams.rb', line 44 def turbo_stream TurboStreams.new(self) end |