Class: Cybertrain::Params

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

Overview

The request parameters, Controller#params in an action and params in a template. They come from the query string, a urlencoded form body and the route’s segments (:id, :article_id), later sources winning. A multipart/form-data body fills them too: its text fields as Strings and its files as UploadedFiles (#upload). A JSON body is not parsed into them.

Values are Strings (never Integers or booleans) or uploaded files. Rails-style keys nest: article[title]=Hi is params.require(:article)[:title], and tags[]=a&tags[]=b is params.list(:tags). A key is one kind at a time, a String, a list, a nested Params or an uploaded file; the last one sent wins.

Malformed input (a bad % escape, invalid UTF-8, more than 32 levels of nesting or 4096 pairs) is answered with 400 before the action runs.

Examples:

Strong parameters, as the scaffold writes them

def article_params
  params.require(:article).permit(:title, :body)
end

Defined Under Namespace

Classes: ParameterMissing

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.max_page ⇒ Integer

Returns the largest page number accepted (Config#max_page).

Returns:

  • (Integer) —

    the largest page number accepted (Config#max_page)



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

def self.max_page
  @max_page
end

.max_page=(n) ⇒ nil

Installs the page ceiling. Called by Application#boot with Config#max_page; a test may call it directly.

Parameters:

Returns:

  • (nil)


158
159
160
161
# File 'cybertrain/params.rb', line 158

def self.max_page=(n)
  @max_page = n < 1 ? 1 : n
  nil
end

.parse_int(text, default) ⇒ Integer

A decimal Integer from text, or default when text is not an optional - and 1 to MAX_INT_DIGITS ASCII digits. Never raises: the length is checked before to_i (NOTES rule 25). Shared with Config.

Parameters:

Returns:



220
221
222
223
224
225
# File 'cybertrain/params.rb', line 220

def self.parse_int(text, default)
  s = text.to_s
  return default unless Params.int_text?(s)

  s.to_i
end

Instance Method Details

#[](key) ⇒ String?

A String value. A list or nested key gives nil, as does an absent one; a key sent with no = gives "".

Examples:

Article.find(params[:id])

Parameters:

  • key (String, Symbol)

Returns:

  • (String, nil)


60
61
62
# File 'cybertrain/params.rb', line 60

def [](key)
  @values[key.to_s]
end

#empty? ⇒ Boolean

Returns true when nothing was sent at this level (a file counts, so require(:post) succeeds for a form that sent only one).

Returns:

  • (Boolean) —

    true when nothing was sent at this level (a file counts, so require(:post) succeeds for a form that sent only one)



509
510
511
# File 'cybertrain/params.rb', line 509

def empty?
  @values.empty? && @lists.empty? && @children.empty? && @uploads.empty?
end

#expect(spec) ⇒ Hash{String => Object}

Rails 8’s strong parameters in one call: the nested level under the spec’s one key, permitted by the spec’s filters as #permit does, which must be present and permit something. A spec of a bare key (expect(:id)) reads one String instead, and answers it as a one-entry Hash ({"id" => "3"}); expect(tags: []) answers a non-empty list the same way ({"tags" => ["a"]}).

Examples:

def article_params
  params.expect(article: [:title, :body, tags: []])
end

Parameters:

  • spec (Hash{Symbol => Array}, Symbol, String) —

    one key

Returns:

  • (Hash{String => Object}) —

    as #permit’s

Raises:

  • (ParameterMissing) —

    "param is missing or the value is empty or invalid: article" (a 400 unless rescued) when the key is absent, of the wrong kind (a String where a nested level is expected, a nested level where a list is), or permits nothing

  • (ArgumentError) —

    when spec is a Hash of more or fewer than one key, its value is not an Array (expect(article: :title)), or a filter has another shape than #permit takes: a mistake in the code, never answered as a 400



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'cybertrain/params.rb', line 291

def expect(spec)
  case spec
  when Hash
    names = spec.keys
    if names.length != 1
      msg = "expect takes a spec of one key, got #{names.length}"
      raise ArgumentError, msg
    end
    name = names[0]
    k = name.to_s
    filters = spec[name]
    case filters
    when Array
      if filters.empty?
        list = @lists[k]
        Params.expect_missing!(k) if list.nil? || list.empty?
        out = Params.permitted_hash
        out[k] = Params.copy_strings(list)
        return out
      end
      child = @children[k]
      Params.expect_missing!(k) if child.nil?
      permitted = child.permitted_by(filters)
      Params.expect_missing!(k) if permitted.empty?
      return permitted
    end
    Params.filter_not_array!("expect", k, filters.class.name.to_s)
    Params.permitted_hash
  else
    k = spec.to_s
    v = @values[k]
    Params.expect_missing!(k) if v.nil? || v.empty?
    out = Params.permitted_hash
    out[k] = v
    out
  end
end

#int(key, default:, min:, max:) ⇒ Integer

A String value read as a decimal Integer, bounded: default when the key is absent or its value is not an optional - followed by 1 to 18 digits ("12abc", " 3", "1e3", "" and a 30-digit number all give default, and nothing ever raises), else the number clamped to min..max. Request data is never handed to to_i unchecked, since past 2**63-1 that raises RangeError (a 500) under Spinel.

Examples:

per = params.int(:per, default: 20, min: 1, max: 100)

Parameters:

Returns:



182
183
184
# File 'cybertrain/params.rb', line 182

def int(key, default:, min:, max:)
  Params.clamp_int(@values[key.to_s], default, min, max)
end

#key?(key) ⇒ Boolean

Returns true when the key was sent, of any kind.

Parameters:

  • key (String, Symbol)

Returns:

  • (Boolean) —

    true when the key was sent, of any kind



89
90
91
92
# File 'cybertrain/params.rb', line 89

def key?(key)
  k = key.to_s
  @values.key?(k) || @lists.key?(k) || @children.key?(k) || @uploads.key?(k)
end

#list(key) ⇒ Array<String>

The values sent as key[]=a&key[]=b.

Parameters:

  • key (String, Symbol)

Returns:

  • (Array<String>) —

    [] when absent



68
69
70
71
# File 'cybertrain/params.rb', line 68

def list(key)
  arr = @lists[key.to_s]
  arr.nil? ? [] : arr
end

#nested(key) ⇒ Params

The nested parameters sent as key[...], like #require but without raising.

A fresh, empty Params for an absent key – it is never stored, so calling #nested twice on the same missing key returns two different (both empty) objects.

Parameters:

  • key (String, Symbol)

Returns:



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

def nested(key)
  @children[key.to_s] || Params.new
end

#page_number ⇒ Integer

The 1-based page number from ?page=N, for Relation#page: 1 when page is absent or not a number, else clamped to 1..Params.max_page (Config#max_page). Reads the key page only.

Examples:

@page = Article.order("id DESC").page(params.page_number, per: 20)

Returns:



193
194
195
196
197
# File 'cybertrain/params.rb', line 193

def page_number
  # The literal key, not int(:page, ...): one method fed Symbol and
  # String keys in one program mis-dispatches its key.to_s (NOTES rule 51).
  Params.clamp_int(@values["page"], 1, 1, Params.max_page)
end

#permit(*keys) ⇒ Hash{String => Object}

The listed keys, as a Hash ready for Model.new or Model#update. A Symbol or String key permits a String value; key: [] permits a list of Strings (key[]=a&key[]=b); key: [:a, b: []] permits a nested level by the same rules, as a nested Hash. A value of another kind than the one permitted (a list sent where a String is permitted, a String where a nested level is) is dropped, not coerced, and so are unlisted keys and uploaded files: read a file with #upload.

A filter is a key or a Hash of key => Array: permit(meta: :source) (the nested level’s filters not in an Array) and an Array among the filters (permit([:title]), [[:title]], Rails 8’s list of records) are ArgumentErrors, a mistake in the code rather than in the request.

Examples:

params.require(:article).permit(:title, :body)  # => {"title" => "Hi", "body" => "..."}
params.require(:article).permit(:title, tags: [], meta: [:source])
# => {"title" => "Hi", "tags" => ["a", "b"], "meta" => {"source" => "rss"}}

Parameters:

  • keys (Array<String, Symbol, Hash{Symbol => Array}>)

Returns:

  • (Hash{String => Object}) —

    values are Strings, Arrays of Strings, or nested Hashes of the same

Raises:

  • (ArgumentError) —

    for a filter of another shape (see above)



266
267
268
# File 'cybertrain/params.rb', line 266

def permit(*keys)
  permitted_by(keys)
end

#require(key) ⇒ Params

The nested parameters under key (article[...]), which must be present and non-empty. Only nested keys qualify: require(:id) raises even when id was sent, since it is a String.

Parameters:

  • key (String, Symbol)

Returns:

Raises:

  • (ParameterMissing) —

    "param is missing or the value is empty: article" (a 400 unless rescued)



102
103
104
105
106
107
108
109
# File 'cybertrain/params.rb', line 102

def require(key)
  k = key.to_s
  child = @children[k]
  if child.nil? || child.empty?
    raise ParameterMissing, "param is missing or the value is empty: #{k}"
  end
  child
end

#to_h ⇒ Hash{String => String}

This level’s String values as a Hash (not the lists or nested parameters).

Params has no keys method on purpose: it would share its name with Hash#keys in a class whose own code (to_h, inspect, merge!) calls Hash#keys on its Hashes, the shape NOTES rule 51 records as mis-dispatching under Spinel. Ask key? for one name, or to_h / inspect for the whole level.

Returns:

  • (Hash{String => String})


500
501
502
503
504
# File 'cybertrain/params.rb', line 500

def to_h
  h = {}
  @values.keys.each { |k| h[k] = @values[k] }
  h
end

#upload(key) ⇒ UploadedFile?

The file sent as key in a multipart body. The same value is never also a String: #[] gives nil for it, and #permit never returns it, so a file reaches a model only through an explicit call such as post.cover_file = params.nested(:post).upload(:cover).

A file input left empty (the browser sends filename=”” and no bytes when nothing was chosen) is dropped by the multipart parser, so this is nil for it. A form whose only field is that file then has no post key at all: read an optional file through #nested, which does not raise, rather than #require. A chosen file with no bytes is kept, as a file whose UploadedFile#empty? is true.

Examples:

file = params.nested(:post).upload(:cover)
@post.cover_file = file if file

Parameters:

  • key (String, Symbol)

Returns:

  • (UploadedFile, nil) —

    nil when no file was sent under that name



128
129
130
# File 'cybertrain/params.rb', line 128

def upload(key)
  @uploads[key.to_s]
end

#upload?(key) ⇒ Boolean

Returns true when a file was sent under that name (even a chosen file with no bytes; never an input left empty).

Parameters:

  • key (String, Symbol)

Returns:

  • (Boolean) —

    true when a file was sent under that name (even a chosen file with no bytes; never an input left empty)



136
137
138
# File 'cybertrain/params.rb', line 136

def upload?(key)
  @uploads.key?(key.to_s)
end