Module: Cybertrain::Cast

Defined in:
cybertrain/cast.rb

Overview

Converts loosely typed values (SQLite cells, form strings) into the one concrete type each model attribute holds. Generated models call these from load_row/write_attribute; nullable attributes go through the *_or_nil variants because Spinel needs a nullable ivar assigned through a helper that can return nil (spikes/NOTES.md rule 7).

Class Method Summary collapse

Class Method Details

.array(v) ⇒ Array<Object>

hash for Arrays: v’s elements in a fresh empty_array, or that empty Array when v is not an Array.

Parameters:

  • v (Object)

Returns:

  • (Array<Object>)


636
637
638
639
640
641
642
643
# File 'cybertrain/cast.rb', line 636

def self.array(v)
  out = empty_array
  case v
  when Time then nil
  when Array then v.each { |x| out << x }
  end
  out
end

.binary(v) ⇒ String

A binary (BLOB) cell or attribute as its bytes: the String itself (a BLOB cell from Connection#execute is a String of the exact bytes), a DB::Blob’s bytes, “” for nil.

Parameters:

Returns:

  • (String)


62
63
64
65
66
67
68
69
# File 'cybertrain/cast.rb', line 62

def self.binary(v)
  case v
  when nil then ""
  when String then v
  when DB::Blob then v.blob_bytes
  else v.to_s
  end
end

.binary_or_nil(v) ⇒ String?

binary for a nullable binary column: nil stays nil (NULL); a String is its bytes, a DB::Blob its blob_bytes (so an assigned Blob binds its bytes, never its inspect text), anything else to_s.

Parameters:

Returns:

  • (String, nil)


77
78
79
80
81
82
83
84
# File 'cybertrain/cast.rb', line 77

def self.binary_or_nil(v)
  case v
  when nil then nil
  when String then v
  when DB::Blob then v.blob_bytes
  else v.to_s
  end
end

.binds(*values) ⇒ Array<Object>

The bind Array Connection#execute takes, each value through to_sql (a Time in the storage format, a Date as its text, a Hash as JSON, booleans as 1/0). A splat compiles under Spinel (Params#permit takes one too); the result is the polymorphic Array, seeded so it stays one when every argument has the same type. A DB::Blob passes through and binds as a BLOB.

Examples:

sql = "SELECT COUNT(*) AS n FROM stats WHERE project_id = ? AND at >= ?"
Cybertrain::DB.with { |c| c.execute(sql, Cybertrain::Cast.binds(project.id, since)) }

Parameters:

  • values (Array<Object>) —

    nil, Integer, Float, String, true/false, Time, Date, Hash or DB::Blob

Returns:

  • (Array<Object>)


435
436
437
438
439
440
# File 'cybertrain/cast.rb', line 435

def self.binds(*values)
  out = [nil, 0, 0.0, "", DB::Blob.new("")]
  out.clear
  values.each { |v| out << to_sql(v) }
  out
end

.date(v) ⇒ Date

A DATE cell or attribute: a Date as is, YYYY-MM-DD text as that Date, and Date.new(1970, 1, 1) for anything else, so a NOT NULL column holding a corrupt cell does not take the row down.

Parameters:

  • v (Date, String, nil)

Returns:



347
348
349
350
# File 'cybertrain/cast.rb', line 347

def self.date(v)
  d = date_or_nil(v)
  d.nil? ? Date.new(1970, 1, 1) : d
end

.date_or_nil(v) ⇒ Date?

date for a nullable column: a Date as is, YYYY-MM-DD text (strict: no other shape, valid month and day) as that Date, nil for anything else. when Time first (NOTES rule 8): a Time is not a Date.

Parameters:

  • v (Date, String, nil)

Returns:



358
359
360
361
362
363
364
365
# File 'cybertrain/cast.rb', line 358

def self.date_or_nil(v)
  case v
  when Time then nil
  when Date then v
  when String then parse_date(v.to_s)
  else nil
  end
end

.empty_array ⇒ Array<Object>

A fresh empty Array of any values (array’s fallback), seeded like empty_hash.

Returns:

  • (Array<Object>)


488
489
490
491
492
# File 'cybertrain/cast.rb', line 488

def self.empty_array
  a = [[nil, 0, 0.0, "", true][0]]
  a.clear
  a
end

.empty_hash ⇒ Hash{String => Object}

A fresh empty Hash typed String => any value, what hash returns for a value that is not a Hash. Seeded with a value of every scalar type (NOTES rules 9 and 46), so spinel --emit-rbs reads it as Hash[String, untyped] rather than an empty literal’s guess.

Returns:

  • (Hash{String => Object})


478
479
480
481
482
# File 'cybertrain/cast.rb', line 478

def self.empty_hash
  h = { "" => [nil, 0, 0.0, "", true][0] }
  h.delete("")
  h
end

.hash(v) ⇒ Hash{String => Object}

Narrows a parsed JSON value (or any polymorphic one) to a Hash: its pairs, keys through to_s, copied into a fresh empty_hash, or that empty Hash when v is not a Hash. A copy, not v itself: the copy is typed Hash[String, untyped] for the compiler, where handing back the boxed v leaves every later call on it on the slow path. It is shallow (nested containers are shared). when Time comes before the container branches (NOTES rule 8).

Examples:

doc = Cybertrain::Cast.hash(JSON.parse(body))
tags = Cybertrain::Cast.array(doc["tags"])

Parameters:

  • v (Object)

Returns:

  • (Hash{String => Object})


507
508
509
510
511
512
513
514
# File 'cybertrain/cast.rb', line 507

def self.hash(v)
  out = empty_hash
  case v
  when Time then nil
  when Hash then v.each { |k, x| out[k.to_s] = x }
  end
  out
end

.hash_or_nil(v) ⇒ Hash{String => Object}?

hash for a nullable json column: nil for nil and ""; a String is JSON text, parsed and then narrowed by hash (a non-object root or invalid JSON is {}, no exception); any other value goes to hash as it is.

Examples:

meta = Cybertrain::Cast.hash_or_nil(row["meta"])

Parameters:

  • v (String, Hash, nil)

Returns:

  • (Hash{String => Object}, nil)


525
526
527
528
529
530
531
532
533
534
# File 'cybertrain/cast.rb', line 525

def self.hash_or_nil(v)
  case v
  when nil then nil
  when Time then hash(v)
  when String
    text = v.to_s
    text.empty? ? nil : hash(parse_json(text))
  else hash(v)
  end
end

.iso8601(time) ⇒ String

The display format of a datetime, Rails’ as_json: UTC, T, milliseconds, Z (2026-10-05T09:00:00.123Z). as_json, to_json and str use it; storage uses sql_datetime.

Parameters:

Returns:

  • (String)


177
178
179
# File 'cybertrain/cast.rb', line 177

def self.iso8601(time)
  time.getutc.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
end

.json_hash(v) ⇒ Hash{String => Object}

A NOT NULL json column’s value as a Hash: a Hash’s pairs (keys through to_s, hash’s typed copy); a String is the stored JSON text, parsed and then narrowed by hash, so an object root is its Hash and an array or scalar root, invalid JSON or "" is {} (a corrupt cell does not take the row down); anything else is {}. hash alone would read the stored text as {}. when Time first (NOTES rule 8).

Examples:

meta = Cybertrain::Cast.json_hash(row["meta"])

Parameters:

  • v (String, Hash, nil)

Returns:

  • (Hash{String => Object})


621
622
623
624
625
626
627
628
629
# File 'cybertrain/cast.rb', line 621

def self.json_hash(v)
  case v
  when Time then empty_hash
  when String
    text = v.to_s
    text.empty? ? empty_hash : hash(parse_json(text))
  else hash(v)
  end
end

.json_text(v) ⇒ String?

A json column’s stored text: JSON.generate of a Hash, nil for nil (SQL NULL); any other value is narrowed by hash first ({}).

Parameters:

  • v (Hash, nil)

Returns:

  • (String, nil)


551
552
553
554
555
556
557
558
# File 'cybertrain/cast.rb', line 551

def self.json_text(v)
  case v
  when nil then nil
  when Time then JSON.generate(hash(v))
  when Hash then JSON.generate(v)
  else JSON.generate(hash(v))
  end
end

.like_escape(text) ⇒ String

text with \, % and _ escaped by a backslash, for a LIKE pattern written with ESCAPE '\'. Relation#where_like wraps it in %...%; a prefix search writes its own pattern:

Examples:

pattern = Cybertrain::Cast.like_escape(params[:q]) + "%"
Article.all.where_sql("title LIKE ? ESCAPE '\\'", [pattern])

Parameters:

  • text (String)

Returns:

  • (String)


451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'cybertrain/cast.rb', line 451

def self.like_escape(text)
  s = text.to_s # NOTES rule 62: a boxed String argument (request data)
  out = +""
  i = 0
  n = s.bytesize
  start = 0
  while i < n
    b = s.getbyte(i)
    # 92 `\`, 37 `%`, 95 `_`: ASCII bytes, so the byteslice boundaries
    # around them are character boundaries.
    if b == 92 || b == 37 || b == 95
      out << s.byteslice(start, i - start) if i > start
      out << "\\"
      start = i
    end
    i += 1
  end
  out << s.byteslice(start, n - start) if n > start
  out
end

.parse_rfc2822(text) ⇒ Time?

RFC 2822 (Thu, 05 Nov 2026 09:00:00 +0000): the English day name and a comma, a one- or two-digit day, the English month name, a four-digit year, HH:MM:SS, and a +HHMM / -HHMM offset (or GMT / UT), single spaces between. The answer is in UTC; anything else is nil. Bytes, as in parse_time.

Parameters:

  • text (String)

Returns:



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'cybertrain/cast.rb', line 281

def self.parse_rfc2822(text)
  s = text.to_s # NOTES rule 62, as in parse_time
  n = s.bytesize
  return nil if n < 26
  return nil unless RFC2822_DAYS.include?(s.byteslice(0, 3)) && s.getbyte(3) == 44 && s.getbyte(4) == 32
  i = 5
  day_len = s.getbyte(6) == 32 ? 1 : 2
  day = number_at(s, i, day_len)
  i += day_len
  return nil unless s.getbyte(i) == 32
  month = month_at(s, i + 1)
  return nil if month < 0
  i += 4
  return nil unless s.getbyte(i) == 32 && s.getbyte(i + 5) == 32
  year = number_at(s, i + 1, 4)
  i += 6
  return nil if n < i + 9
  return nil unless s.getbyte(i + 2) == 58 && s.getbyte(i + 5) == 58 && s.getbyte(i + 8) == 32
  hour = number_at(s, i, 2)
  minute = number_at(s, i + 3, 2)
  second = number_at(s, i + 6, 2)
  i += 9
  zone = s.byteslice(i, n - i)
  offset = if zone == "GMT" || zone == "UT"
             0
           elsif n - i == 5
             offset_at(s, i)
           else
             OFFSET_INVALID
           end
  return nil if offset == OFFSET_INVALID
  utc_time(year, month, day, hour, minute, second, 0, offset)
end

.parse_time(text) ⇒ Time?

YYYY-MM-DD[T ]HH:MM:SS, then an optional . and 1 to 9 fraction digits (the first six kept: microseconds), then an optional Z, +HH:MM, -HH:MM, +HHMM or -HHMM (applied: the answer is the same instant in UTC), and nothing after it. A String whose fourth byte is , is read as RFC 2822 instead (parse_rfc2822). Anything else is nil. The C reader cybertrain_sqlite_column_epoch (db/sqlite_ffi.rb) accepts the same shapes.

Checks the shape and the ranges (month, day of that month, hour, minute, second) before calling Time.utc, which raises on out-of-range fields: a bad cell or form value must read as nil, not crash.

Reads bytes, not substrings: every datetime column of every loaded row comes through here, and slicing out six fields (plus a one-character String per digit for the check) was a tenth of an article page’s time. The bytes it accepts are all ASCII, so a multibyte String is refused exactly as the character-indexed version refused it.

The argument is read through a to_s local: it is often boxed (a value out of JSON.parse or a Hash of mixed values, or what Cast.str hands back: when String then v returns the boxed v), and a boxed getbyte raises NoMethodError in a program that requires the openssl package (spikes/NOTES.md rule 62). For a String, to_s is no copy.

Parameters:

  • text (String)

Returns:



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'cybertrain/cast.rb', line 207

def self.parse_time(text)
  s = text.to_s
  n = s.bytesize
  return parse_rfc2822(s) if n > 3 && s.getbyte(3) == 44
  return nil if n < 19
  return nil unless s.getbyte(4) == 45 && s.getbyte(7) == 45 && s.getbyte(13) == 58 && s.getbyte(16) == 58
  sep = s.getbyte(10)
  return nil unless sep == 84 || sep == 32

  i = 19
  usec = 0
  if i < n && s.getbyte(i) == 46
    start = i + 1
    i = start
    i += 1 while i < n && i - start < 10 && s.getbyte(i) >= 48 && s.getbyte(i) <= 57
    digits = i - start
    return nil if digits == 0 || digits > 9
    kept = digits < 6 ? digits : 6
    # A table, not a `usec *= 10` loop: Spinel types an Integer
    # multiplied in an unbounded loop as a Bigint.
    usec = number_at(s, start, kept) * FRACTION_SCALE[kept]
  end
  offset = 0
  if i < n
    offset = offset_at(s, i)
    return nil if offset == OFFSET_INVALID
  end
  utc_time(number_at(s, 0, 4), number_at(s, 5, 2), number_at(s, 8, 2),
           number_at(s, 11, 2), number_at(s, 14, 2), number_at(s, 17, 2), usec, offset)
end

.round_scale(v, scale) ⇒ Float

A decimal value rounded to the column’s scale: v as a Float, rounded half away from zero on its decimal digits (round_digits); a negative scale (none declared) and a non-finite value ("1e999") are left as they are. The contract of a decimal column is docs/design.md D73.

Examples:

Cast.round_scale("1.005", 2)  # => 1.01
Cast.round_scale(2.6, 0)      # => 3.0

Parameters:

Returns:

  • (Float)


572
573
574
575
# File 'cybertrain/cast.rb', line 572

def self.round_scale(v, scale)
  f = float(v)
  (scale < 0 || !f.finite?) ? f : round_digits(f, scale)
end

.round_scale_or_nil(v, scale) ⇒ Float?

round_scale for a nullable decimal column: nil (and "", an empty form field) stay nil, so an unset value is stored as NULL, never 0.0; anything else is float_or_nil’s Float rounded to scale.

Parameters:

Returns:

  • (Float, nil)


585
586
587
588
589
590
# File 'cybertrain/cast.rb', line 585

def self.round_scale_or_nil(v, scale)
  f = float_or_nil(v)
  return nil if f.nil?

  (scale < 0 || !f.finite?) ? f : round_digits(f, scale)
end

.sql_datetime(time) ⇒ String

The storage format of a datetime, the one Rails writes to SQLite: UTC, a space, six fraction digits, no suffix (2026-10-05 09:00:00.123456). Every writer of a DATETIME column binds this; it sorts as text in time order.

Parameters:

Returns:

  • (String)


167
168
169
# File 'cybertrain/cast.rb', line 167

def self.sql_datetime(time)
  time.getutc.strftime("%Y-%m-%d %H:%M:%S.%6N")
end

.time_or_nil(v) ⇒ Time?

Time as is; Integer as epoch seconds; a String through parse_time (ISO 8601 with T or a space, a fraction, Z or an offset; RFC 2822); anything else is nil.

Parameters:

Returns:



130
131
132
133
134
135
136
137
138
139
# File 'cybertrain/cast.rb', line 130

def self.time_or_nil(v)
  case v
  when Time then v
  when Integer then Time.at(v).utc
  # v.to_s so parse_time's parameter is a String, not the polymorphic
  # v: its byte reads are then plain C (see Html.escape).
  when String then parse_time(v.to_s)
  else nil
  end
end

.to_sql(v) ⇒ Object

The value to bind for a column: a Time in the storage format (sql_datetime), a Date as YYYY-MM-DD, a Hash as its JSON text (json_text), booleans as 1/0; nil, Integer, Float and String pass through. when Time comes before the container branch (NOTES rule 8).

Parameters:

  • v (Object)

Returns:

  • (Object)


149
150
151
152
153
154
155
156
157
158
# File 'cybertrain/cast.rb', line 149

def self.to_sql(v)
  case v
  when Time then sql_datetime(v)
  when Date then v.to_s
  when Hash then json_text(v)
  when true then 1
  when false then 0
  else v
  end
end