Class: Cybertrain::Request

Inherits:
Object
  • Object
show all
Defined in:
cybertrain/http/request.rb

Overview

One incoming HTTP request. Header names are expected lowercased (as HttpParser produces them), but #header also finds mixed-case keys so hand-built requests in tests behave the same.

Controller#request in an action. Read parameters through Controller#params; the request holds the raw parts. The client’s address is #client_ip (Rails’ remote_ip, with one trusted proxy hop at most, see Request.trusted_proxy and Request.trusted_proxies). There is no xhr? or url.

Examples:

request.header("user-agent")
JSON.parse(request.body) if request.json?   # JSON bodies are not parsed into params
JSON.parse(request.decoded_body)            # the same for a gzip-compressed body

Constant Summary collapse

MAX_DECODED_BODY_BYTES =

The largest decoded body #decoded_body returns by default, 10 MiB, the same as the server’s default limit on the body as sent (Config#max_body_bytes). An endpoint that expects more passes its own limit (at most 2 GiB - 1, what the inflater can hand back), sized to its payload: inflating costs about 1.4 ms per MiB of output and runs in C without yielding, so a large default would let a small body keep the worker busy.

10_485_760
MAX_PARAM_HEADER_BYTES =

The longest header value #header_params and #header_scheme parse, 8 KiB; a longer one gives an empty result.

8192

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#body ⇒ String (readonly)

The raw body ("" when there is none).

Returns:

  • (String)


77
78
79
# File 'cybertrain/http/request.rb', line 77

def body
  @body
end

#format_extension ⇒ String

The extension the route split off the last path segment ("json" for /articles/3.json), "" for none or before routing.

Returns:

  • (String)


149
150
151
# File 'cybertrain/http/request.rb', line 149

def format_extension
  @format_extension
end

#headers ⇒ Hash{String => String} (readonly)

The headers, by lowercase name. #header looks one up.

Returns:

  • (Hash{String => String})


72
73
74
# File 'cybertrain/http/request.rb', line 72

def headers
  @headers
end

#method ⇒ String (readonly)

The method, upper case, after a form’s _method override (so "PATCH" for an edit form).

Returns:

  • (String)


57
58
59
# File 'cybertrain/http/request.rb', line 57

def method
  @method
end

#path ⇒ String (readonly)

The path as sent, without the query string and not percent-decoded.

Returns:

  • (String)


62
63
64
# File 'cybertrain/http/request.rb', line 62

def path
  @path
end

#query_string ⇒ String (readonly)

The raw query string, without the ? ("" when there is none).

Returns:

  • (String)


67
68
69
# File 'cybertrain/http/request.rb', line 67

def query_string
  @query_string
end

#remote_addr ⇒ String (readonly)

The peer’s IP address (the reverse proxy’s, behind one).

Returns:

  • (String)


82
83
84
# File 'cybertrain/http/request.rb', line 82

def remote_addr
  @remote_addr
end

#request_id ⇒ String

The request’s id (spec section 12.2): a UUID that Cybertrain::RequestId made, or the X-Request-Id a trusted proxy sent (1 to 255 letters, digits and hyphens); the response’s X-Request-Id echoes it, and every line logged during the request carries it. "" until the RequestId middleware has run.

Examples:

Cybertrain.logger.info("export for #{request.request_id}")

Returns:

  • (String)


95
96
97
# File 'cybertrain/http/request.rb', line 95

def request_id
  @request_id
end

Class Method Details

.format_for_extension(ext) ⇒ Symbol

The registered format of an extension, Rails’ MIME table ("json" -> :json, "jpg" -> :jpeg, "txt" -> :text), :unknown for any other: a fixed table, so request input never becomes a new Symbol.

Parameters:

  • ext (String) —

    without the dot, as written (case matters)

Returns:

  • (Symbol)


349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'cybertrain/http/request.rb', line 349

def self.format_for_extension(ext)
  case ext
  when "html", "htm" then :html
  when "text", "txt" then :text
  when "js" then :js
  when "css" then :css
  when "ics" then :ics
  when "csv" then :csv
  when "vcf" then :vcf
  when "vtt" then :vtt
  when "png" then :png
  when "jpeg", "jpg" then :jpeg
  when "gif" then :gif
  when "bmp" then :bmp
  when "tiff" then :tiff
  when "svg" then :svg
  when "webp" then :webp
  when "mpeg" then :mpeg
  when "mp3" then :mp3
  when "ogg" then :ogg
  when "m4a" then :m4a
  when "webm" then :webm
  when "mp4" then :mp4
  when "otf" then :otf
  when "ttf" then :ttf
  when "woff" then :woff
  when "woff2" then :woff2
  when "xml" then :xml
  when "rss" then :rss
  when "atom" then :atom
  when "yaml" then :yaml
  when "multipart_form" then :multipart_form
  when "url_encoded_form" then :url_encoded_form
  when "json" then :json
  when "pdf" then :pdf
  when "zip" then :zip
  when "gzip" then :gzip
  when "turbo_stream" then :turbo_stream
  else :unknown
  end
end

.http_date(time) ⇒ String

An HTTP date (RFC 9110 section 5.6.7, IMF-fixdate), what Last-Modified and Expires carry: Sun, 06 Nov 1994 08:49:37 GMT.

Examples:

Request.http_date(Time.at(784111777)) # => "Sun, 06 Nov 1994 08:49:37 GMT"

Parameters:

Returns:

  • (String)


739
740
741
# File 'cybertrain/http/request.rb', line 739

def self.http_date(time)
  time.getutc.strftime("%a, %d %b %Y %H:%M:%S GMT")
end

.mime_type(format) ⇒ String

The Content-Type a response in format is sent with (:json -> "application/json; charset=utf-8"); "application/octet-stream" for a format without a text type here.

Parameters:

  • format (Symbol)

Returns:

  • (String)


397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'cybertrain/http/request.rb', line 397

def self.mime_type(format)
  case format
  when :html then "text/html; charset=utf-8"
  when :json then "application/json; charset=utf-8"
  when :turbo_stream then "text/vnd.turbo-stream.html; charset=utf-8"
  when :csv then "text/csv; charset=utf-8"
  when :xml then "application/xml; charset=utf-8"
  when :text then "text/plain; charset=utf-8"
  when :js then "text/javascript; charset=utf-8"
  when :css then "text/css; charset=utf-8"
  else "application/octet-stream"
  end
end

.parse_http_date(text) ⇒ Integer

The epoch seconds of an HTTP date as http_date writes it (a conditional request’s If-Modified-Since), -1 when the text is not one. An Integer sentinel, not nil, so the result has one type.

Examples:

Request.parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT") # => 784111777
Request.parse_http_date("yesterday")                      # => -1

Parameters:

  • text (String)

Returns:



752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
# File 'cybertrain/http/request.rb', line 752

def self.parse_http_date(text)
  s = text.to_s # NOTES rule 62: the byte scans read a fresh local
  return -1 unless s.bytesize == 29 && s.getbyte(3) == 44 && s.getbyte(4) == 32 && s.getbyte(7) == 32 &&
                   s.getbyte(11) == 32 && s.getbyte(16) == 32 && s.getbyte(19) == 58 && s.getbyte(22) == 58 &&
                   s.getbyte(25) == 32 && s.byteslice(25, 4) == " GMT"
  return -1 unless HTTP_DAYS.include?(s.byteslice(0, 3))

  month = 0
  name = s.byteslice(8, 3)
  m = 0
  while m < 12
    month = m + 1 if HTTP_MONTHS[m] == name
    m += 1
  end
  return -1 if month == 0

  day = http_digits(s, 5, 2)
  year = http_digits(s, 12, 4)
  hour = http_digits(s, 17, 2)
  minute = http_digits(s, 20, 2)
  second = http_digits(s, 23, 2)
  return -1 if day < 1 || day > 31 || year < 1970 || hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 60

  # Days from the civil date (Howard Hinnant's algorithm), then seconds.
  y = month <= 2 ? year - 1 : year
  era = y / 400
  yoe = y - era * 400
  shifted = month > 2 ? month - 3 : month + 9
  doy = (153 * shifted + 2) / 5 + day - 1
  doe = yoe * 365 + yoe / 4 - yoe / 100 + doy
  days = era * 146_097 + doe - 719_468
  days * 86_400 + hour * 3600 + minute * 60 + second
end

.trusted_proxies ⇒ Array<String>

Returns the addresses and CIDRs whose connections may name the client in X-Forwarded-For (#client_ip); Config#trusted_proxies.

Returns:

  • (Array<String>) —

    the addresses and CIDRs whose connections may name the client in X-Forwarded-For (#client_ip); Config#trusted_proxies



1137
1138
1139
# File 'cybertrain/http/request.rb', line 1137

def self.trusted_proxies
  @trusted_proxy_entries
end

.trusted_proxies=(entries) ⇒ nil

Installs the trusted proxy list: IPv4 or IPv6 addresses or CIDRs (“172.16.0.0/12”, “10.0.0.0/8”, “172.18.0.2”, “fd00::/8”). Called by Application#boot with Config#trusted_proxies, which refuses a bad entry at boot; a test may call it directly. An IPv4 entry also matches its IPv4-mapped IPv6 form (::ffff:172.18.0.2).

Parameters:

  • entries (Array<String>)

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    when an entry is not an address or CIDR



1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
# File 'cybertrain/http/request.rb', line 1150

def self.trusted_proxies=(entries)
  names = Array.new(0) { "" }
  networks = Array.new(0) { 0 }
  i = 0
  while i < entries.size
    entry = entries[i].to_s
    parsed = IpAddress.parse_network(entry)
    raise ArgumentError, "not an IP address or CIDR: #{entry.inspect}" if parsed.empty?

    names << entry
    parsed.each { |b| networks << b }
    i += 1
  end
  @trusted_proxy_entries = names
  @trusted_networks = networks
  nil
end

.trusted_proxy ⇒ Boolean

Returns whether a loopback peer’s X-Forwarded-For names the client (#client_ip); Config#trusted_proxy.

Returns:

  • (Boolean) —

    whether a loopback peer’s X-Forwarded-For names the client (#client_ip); Config#trusted_proxy



1113
1114
1115
# File 'cybertrain/http/request.rb', line 1113

def self.trusted_proxy
  @trusted_proxy
end

.trusted_proxy=(flag) ⇒ nil

Installs the trusted-proxy flag. Called by Application#boot with Config#trusted_proxy; a test may call it directly.

Parameters:

  • flag (Boolean)

Returns:

  • (nil)


1122
1123
1124
1125
# File 'cybertrain/http/request.rb', line 1122

def self.trusted_proxy=(flag)
  @trusted_proxy = flag == true
  nil
end

Instance Method Details

#base_url ⇒ String

The scheme and host the client used, "http://www.example.com": https when a trusted proxy (as for #client_ip) says so in X-Forwarded-Proto, else http; the host is the Host header (“” when there is none). For absolute URLs (a WebSocket URL from turbo_stream_from ws: true).

Returns:

  • (String)


1202
1203
1204
1205
1206
1207
# File 'cybertrain/http/request.rb', line 1202

def base_url
  host = header("host").to_s
  proto = header("x-forwarded-proto").to_s
  scheme = Request.trusted_peer?(@remote_addr) && proto == "https" ? "https" : "http"
  "#{scheme}://#{host}"
end

#client_ip ⇒ String

Examples:

Session.create!(user_id: user.id, ip_address: request.client_ip)

Returns:

  • (String)


1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
# File 'cybertrain/http/request.rb', line 1224

def client_ip
  addr = @remote_addr
  return addr unless Request.trusted_peer?(addr)

  forwarded = header("x-forwarded-for")
  return addr if forwarded.nil?

  hop = Request.last_forwarded_hop(forwarded)
  hop.empty? ? addr : hop
end

#content_encoding ⇒ String

The Content-Encoding header, lowercase; "" when absent.

Returns:

  • (String)


667
668
669
670
671
672
# File 'cybertrain/http/request.rb', line 667

def content_encoding
  value = header("content-encoding")
  return "" if value.nil?

  value.strip.downcase
end

#content_length ⇒ Integer

The Content-Length header as an Integer.

0 when the header is absent or not a plain non-negative integer. A value of more than 18 digits is reported as 9223372036854775807 without parsing it (Spinel’s String#to_i raises RangeError past 2**63-1, NOTES rule 25; CRuby would return a Bignum): the Server’s 413 limit rejects it either way.

Returns:



642
643
644
645
646
647
648
649
# File 'cybertrain/http/request.rb', line 642

def content_length
  value = header("content-length")
  return 0 if value.nil? || value.empty?
  return 0 unless HttpParser.digits?(value)
  return INT64_MAX if value.bytesize > 18

  value.to_i
end

#content_type ⇒ String

Media type only: “text/html; charset=utf-8” -> “text/html”. Lowercase; "" when absent.

Returns:

  • (String)


655
656
657
658
659
660
661
662
# File 'cybertrain/http/request.rb', line 655

def content_type
  value = header("content-type")
  return "" if value.nil?

  semi = value.index(";")
  value = value[0, semi] unless semi.nil?
  value.strip.downcase
end

The raw Cookie header; parse it with Cookies.parse.

Returns:

  • (String) —

    "" when absent



1332
1333
1334
# File 'cybertrain/http/request.rb', line 1332

def cookie_header
  header("cookie") || ""
end

#decoded_body(limit = MAX_DECODED_BODY_BYTES) ⇒ String

The body with its Content-Encoding undone, once per request: the body itself when there is none (or identity), the inflated bytes for gzip (what an SDK or API client sends past a few kilobytes). The server does not decode on its way in, so an action that does not ask never pays for it; #body stays the bytes as sent.

The result is never larger than limit bytes: a gzip body is inflated by the installed inflater (GzipFFI, zlib streamed with a ceiling on the output, so a body that is small on the wire and huge inflated is refused as soon as the ceiling is reached, not after), and a plain body over the limit is refused as well. The bytes on the wire are bounded separately by the server (Config#max_body_bytes). Other encodings (deflate, br) are not decoded: a 400. A multi-member gzip file is inflated whole; bytes after the last member that are not a member of their own make the body undecodable.

Pass a limit sized to the endpoint’s payload: DEFLATE expands up to about 1032 times, so reaching a 10 MiB ceiling takes a 10 KB body and about 14 ms of the worker’s time (the inflate runs in C and does not yield), which is the cost a hostile client can impose per request.

require "cybertrain" installs the inflater. A program that loads only the HTTP layer answers every gzip body as undecodable (a 400) until it requires cybertrain/http/gzip_ffi and calls GzipFFI.install!.

Examples:

JSON.parse(request.decoded_body)
request.decoded_body(52_428_800)   # an endpoint that takes bodies up to 50 MiB

Parameters:

  • limit (Integer) (defaults to: MAX_DECODED_BODY_BYTES) —

    the largest decoded body accepted, in bytes

Returns:

  • (String)

Raises:

  • (BodyUndecodable) —

    on corrupt gzip data, an encoding that is not decoded here, or a gzip body with no inflater installed (a 400 when unhandled)

  • (BodyTooLarge) —

    when the decoded body would exceed limit (a 400 when unhandled)



709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# File 'cybertrain/http/request.rb', line 709

def decoded_body(limit = MAX_DECODED_BODY_BYTES)
  cached = @decoded_body
  unless cached.nil?
    raise BodyTooLarge, "request body is #{cached.bytesize} bytes, over the limit of #{limit}" if cached.bytesize > limit

    return cached
  end

  encoding = content_encoding
  text = ""
  if encoding == "" || encoding == "identity"
    raise BodyTooLarge, "request body is #{@body.bytesize} bytes, over the limit of #{limit}" if @body.bytesize > limit

    text = @body
  elsif encoding == "gzip" || encoding == "x-gzip"
    text = Request.gunzip(@body, limit)
  else
    raise BodyUndecodable, "Content-Encoding #{encoding.inspect} is not supported (gzip or identity)"
  end
  @decoded_body = text
  text
end

#delete? ⇒ Boolean

Returns:

  • (Boolean)


891
892
893
# File 'cybertrain/http/request.rb', line 891

def delete?
  @method == "DELETE"
end

#form? ⇒ Boolean

Returns true for an application/x-www-form-urlencoded body, the only kind parsed into params.

Returns:

  • (Boolean) —

    true for an application/x-www-form-urlencoded body, the only kind parsed into params



898
899
900
# File 'cybertrain/http/request.rb', line 898

def form?
  content_type == "application/x-www-form-urlencoded"
end

#format ⇒ Symbol

The format the client asked for, as a Symbol: the extension’s registered name (format_for_extension: :json for /articles/3.json, :unknown for one that is not registered), else from Accept, read in order: :turbo_stream when it lists text/vnd.turbo-stream.html, :json when it lists application/json and not text/html before it, else :html (also for */* and no Accept at all). An entry with q=0 is ignored; other q-values do not reorder the list.

Examples:

request.format   # => :json for GET /articles/3.json

Returns:

  • (Symbol)


170
171
172
173
174
175
176
177
178
179
180
181
# File 'cybertrain/http/request.rb', line 170

def format
  return @format_symbol if @format_known

  found = if @format_extension.empty?
            Request.format_for_accept(header("Accept").to_s)
          else
            Request.format_for_extension(@format_extension)
          end
  @format_symbol = found
  @format_known = true
  found
end

#get? ⇒ Boolean

Returns:

  • (Boolean)


861
862
863
# File 'cybertrain/http/request.rb', line 861

def get?
  @method == "GET"
end

#head? ⇒ Boolean

Returns:

  • (Boolean)


873
874
875
# File 'cybertrain/http/request.rb', line 873

def head?
  @method == "HEAD"
end

#header(name) ⇒ String?

Examples:

request.header("Referer")

Parameters:

  • name (String) —

    any case

Returns:

  • (String, nil)


421
422
423
424
425
426
427
428
429
# File 'cybertrain/http/request.rb', line 421

def header(name)
  value = @headers[HeaderName.lower(name)]
  return value unless value.nil?

  @headers.each do |k, v|
    return v if HeaderName.same?(k, name)
  end
  nil
end

#header_params(name) ⇒ Hash{String => String}

The parameters of a parameterised header, Scheme k1=v1, k2="v2" (Authorization: Digest ..., a vendor X-*-Auth header) or k1=v1;k2=v2, k3 (Forwarded, Prefer), as a Hash of lowercase names to values:

  • , and ; both separate parameters (the element structure of Forwarded and Prefer is flattened); the first occurrence of a name wins;
  • a name is a run of token characters (RFC 9110), lowercased; a parameter that does not start with one is skipped;
  • a value is a quoted string, unquoted with each backslash escape (\", \\) undone, or the bytes up to the next separator, spaces and tabs around it trimmed; a name without = maps to "";
  • a leading word followed by a space and more text (the scheme: Digest, Bearer) is not a parameter; #header_scheme reads it. A value that is one word alone (Prefer: respond-async) is a bare parameter, not a scheme;
  • a missing header, or one longer than MAX_PARAM_HEADER_BYTES, gives {}.

Values are bytes as sent: never percent-decoded, and possibly not valid UTF-8. Authorization: Bearer <token> and Basic <base64> are a scheme and a credential, not parameters: read those with #header_scheme and #header.

Examples:

# Authorization: Digest username="Mufasa", realm="a@example.com", nc=00000001
request.header_params("authorization")["username"]   # => "Mufasa"
request.header_scheme("authorization")               # => "Digest"
# Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43
request.header_params("forwarded")["proto"]   # => "http"

Parameters:

  • name (String) —

    the header name, any case

Returns:

  • (Hash{String => String})


470
471
472
# File 'cybertrain/http/request.rb', line 470

def header_params(name)
  Request.parse_header_params(header(name).to_s)
end

#header_scheme(name) ⇒ String

The scheme word that starts a parameterised header, as sent: "Digest" for Authorization: Digest username="x", "Bearer" for Authorization: Bearer abc. "" when the header is missing, longer than MAX_PARAM_HEADER_BYTES, starts with a parameter (k=v, or a word followed by , or ;) or is one word alone. Compare it case-insensitively: schemes are.

Parameters:

  • name (String) —

    the header name, any case

Returns:

  • (String)


483
484
485
486
487
488
489
490
491
492
# File 'cybertrain/http/request.rb', line 483

def header_scheme(name)
  text = header(name).to_s
  return "" if text.bytesize > MAX_PARAM_HEADER_BYTES

  start = Request.skip_blanks(text, 0)
  stop = Request.scheme_end(text, start)
  return "" if stop == start

  text.byteslice(start, stop - start).to_s
end

#json? ⇒ Boolean

Returns true for an application/json body.

Returns:

  • (Boolean) —

    true for an application/json body



904
905
906
# File 'cybertrain/http/request.rb', line 904

def json?
  content_type == "application/json"
end

#loopback? ⇒ Boolean

Whether the connection comes from this machine: #remote_addr is in 127.0.0.0/8, ::1 or an IPv4-mapped ::ffff:127.x.x.x. For pages only an operator on the server should reach (a first-run setup page, an admin endpoint). X-Forwarded-For is never consulted, so behind a proxy on the same host every request is loopback: check #client_ip as well when one is in front.

Examples:

before_action(only: [:setup]) { |c| c.head :forbidden unless c.request.loopback? }

Returns:

  • (Boolean)


1191
1192
1193
# File 'cybertrain/http/request.rb', line 1191

def loopback?
  Request.loopback_address?(@remote_addr)
end

#multipart? ⇒ Boolean

Returns true for a multipart/form-data body (a form with file fields). Its text parts and files reach Controller#params (files through Params#upload); see #multipart_form.

Returns:



912
913
914
# File 'cybertrain/http/request.rb', line 912

def multipart?
  content_type == "multipart/form-data"
end

#multipart_boundary ⇒ String

The boundary of a multipart body, from the full Content-Type header (#content_type drops the parameters); "" when there is none or it is not a valid boundary.

Returns:

  • (String)


921
922
923
# File 'cybertrain/http/request.rb', line 921

def multipart_boundary
  Multipart.boundary_from(header("content-type").to_s)
end

#multipart_form ⇒ MultipartForm

The parsed multipart body, once per request (MethodOverride and CsrfProtection read their one field from it before routing, then the Router fills the controller’s params from the same result). Callers check #multipart? first. The ivar starts as nil and is assigned from a method’s result (NOTES rule 7); a raise is not cached, so every later call raises again and the request still ends as that 400.

A multipart body with a Content-Encoding is refused: the parser works on the bytes as sent and nothing here inflates a body it then slices.

Returns:

Raises:

  • (MultipartMalformed) —

    for an encoded body or a malformed one; the Multipart* faults are client faults, answered 400



938
939
940
941
942
943
944
945
946
947
948
# File 'cybertrain/http/request.rb', line 938

def multipart_form
  cached = @multipart_form
  return cached unless cached.nil?

  enc = content_encoding
  raise MultipartMalformed, "encoded multipart bodies are not supported" unless enc.empty? || enc == "identity"

  form = Multipart.parse(@body, header("content-type").to_s)
  @multipart_form = form
  form
end

#patch? ⇒ Boolean

Returns:

  • (Boolean)


879
880
881
# File 'cybertrain/http/request.rb', line 879

def patch?
  @method == "PATCH"
end

#post? ⇒ Boolean

Returns:

  • (Boolean)


867
868
869
# File 'cybertrain/http/request.rb', line 867

def post?
  @method == "POST"
end

#preferred_locale(available) ⇒ Symbol

The locale the client prefers among available, from Accept-Language: the highest q-value wins and the earlier entry breaks a tie; ja-JP matches :ja (the full tag is tried before its language, ASCII case-insensitively); q=0, * and a malformed entry match nothing. Without a match (no header, junk, nothing available) it answers I18n.default_locale, never nil. Only the first 4 KB and 32 entries are read, and the answer is always an element of available (or the default): request text is compared, never turned into a Symbol. The default comes from I18n (cybertrain/i18n), which the HTTP layer does not require (script/check-http-layer keeps it standalone): a program that calls this loads it, as require "cybertrain" does.

Examples:

request.preferred_locale([:en, :ja])   # "ja-JP, en;q=0.5" => :ja

Parameters:

  • available (Array<Symbol>) —

    the locales the application serves

Returns:

  • (Symbol)


240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'cybertrain/http/request.rb', line 240

def preferred_locale(available)
  raw = header("Accept-Language").to_s
  return I18n.default_locale if raw.empty?

  text = raw.bytesize > LOCALE_HEADER_LIMIT ? raw.byteslice(0, LOCALE_HEADER_LIMIT).to_s : raw
  # A header that is not valid text (or was cut inside a character)
  # cannot be split; it is no preference.
  return I18n.default_locale unless text.valid_encoding?

  best = I18n.default_locale
  best_q = 0
  entries = text.split(",", LOCALE_ENTRY_LIMIT + 1)
  i = 0
  while i < entries.size && i < LOCALE_ENTRY_LIMIT
    parts = entries[i].to_s.split(";")
    i += 1
    next if parts.empty?

    q = 1000
    parts.each_with_index do |param, k|
      next if k == 0

      pair = param.split("=", 2)
      next unless pair.size == 2 && pair[0].to_s.strip.downcase == "q"

      q = Request.quality_thousandths(pair[1].to_s.strip)
    end
    next if q <= best_q

    found = Request.locale_match(parts[0].to_s.strip.downcase, available)
    next if found.nil?

    best = found
    best_q = q
  end
  best
end

#put? ⇒ Boolean

Returns:

  • (Boolean)


885
886
887
# File 'cybertrain/http/request.rb', line 885

def put?
  @method == "PUT"
end