Types beside the code
Ruby never asks what type a value has – any object that answers the right methods will do. That keeps code short, but a mistake can travel a long way before it hurts. Since Ruby 3.0 there is an official language for writing types down: RBS. Signatures live in files of their own, sig/*.rbs, beside the code; the Ruby files stay as they are. Here are the types of the timelog's Entry from lesson 108:
# sig/timelog.rbs class Entry attr_reader project: String attr_reader from: String attr_reader to: String attr_reader note: String? def initialize: (project: String, from: String, to: String, ?note: String?) -> void def hours: () -> Float def to_s: () -> String private def as_hours: (String time) -> Float end
attr_reader project: String– this reader returns a String.def hours: () -> Float– a method's type: the parameters in brackets, after the arrow what it returns.voidsays: don't use the result.project: Stringinside the brackets is a required keyword argument. Positional parameters are written type first, the name is optional documentation:(String time).String?means a String ornil. A?in front of a parameter makes it optional – so?note: String?may be left out, and may benil.
Ruby itself never reads this file. Tools do: Steep checks the code against it without running it, TypeProf guesses signatures from the code, and the rbs gem can check every call while your tests run. First, what happens without them – an hour count read from a form is still a String:
# Ruby itself never looks at types: a wrong argument just travels on
class Shift
attr_reader :project, :hours
def initialize(project, hours)
@project = project
@hours = hours
end
def cost(rate) = hours * rate
end
shift = Shift.new("Bacon", "1.5") # read from a form: still a String
shift.cost(4.0)No error at all: String#* repeats a string, so 1.5 hours at 4.0 an hour cost "1.51.51.51.5". The mistake happened at Shift.new; it shows up, if ever, much later and somewhere else. A type checker with a signature for Shift would have pointed at Shift.new.
More of the language
The Timesheet that collects the entries shows the rest of what you need day to day:
interface _Billable
def hours: () -> Float
end
class Timesheet
include Enumerable[Entry]
@entries: Array[Entry]
def initialize: () -> void
def add: (Entry entry) -> self
def total_for: (String | Symbol project) -> Float
def by_project: () -> Hash[String, Float]
def last_for: (String project) -> Entry?
def pick: () { (Entry) -> bool } -> Array[Entry]
def each: () { (Entry) -> void } -> self
| () -> Enumerator[Entry, self]
def self.sum: (Array[_Billable] items) -> Float
def self.latest: [T] (Array[T] items) -> T?
endArray[Entry],Hash[String, Float],Enumerable[Entry]are generics: a container and, in square brackets, what it holds.@entries: Array[Entry]types an instance variable.String | Symbolis a union: one of them.Entry?is short forEntry | nil–last_formay find nothing.selfas the return type:addreturns the timesheet itself, so calls can be chained.{ (Entry) -> bool } -> Array[Entry]:picktakes a block that gets an Entry and answers true or false.- Two lines joined by
|are overloads:eachwith a block returnsself, without one an Enumerator. interface _Billableputs duck typing into words: anything with anhoursmethod that returns a Float – an Entry, or a Struct from somewhere else. Interface names start with_; Ruby's own signatures have_ToSand_Each.[T] (Array[T] items) -> T?is a generic method: whatever the array holds, one of those (or nil) comes back.
The rbs gem that reads these files has a parser written in C, so it cannot load in this page. But one of its tools is simple at heart: rbs test wraps your methods and checks every call against its signature. That we can build. It starts with a small insight: a type is a test for a value, and Ruby already has that test – ===:
# A type is a test for a value
def type_ok?(value, type)
case type
when "untyped" then true
when "bool" then value == true || value == false
when "nil" then value.nil?
else Object.const_get(type) === value
end
end
# "def cost: (Float) -> Float" => [:cost, ["Float"], "Float"]
def parse_sig(line)
m = line.match(/\Adef (\w+[?!]?): \((.*)\) -> (.+)\z/)
raise ArgumentError, "cannot read #{line.inspect}" unless m
[m[1].to_sym, m[2].split(",").map(&:strip), m[3].strip]
end
p type_ok?(1.5, "Float")
p type_ok?(2, "Float")
p type_ok?("Bacon", "String")
parse_sig("def initialize: (String, Float) -> void")Float === 2 is false: an Integer is not a Float. RBS sees it the same way – nothing is converted, so a method that takes both says Float | Integer (or Numeric). parse_sig reads one line into the name, the parameter types and the return type. It is deliberately small: no parameter names, no keywords, no blocks, no Hash[String, Float] (its comma would split it). Real RBS needs a real parser.
Wrapping with prepend
Now the tester's trick. Module#prepend puts a module in front of a class in the chain Ruby searches for methods (lesson 119): a method in the module runs first, and its super calls the class's own. So for each signature we define a method of the same name in a fresh module, which checks the arguments, calls super and checks the result. We prepend the module to a subclass, CheckedShift, so that the first cell keeps showing the quiet mistake:
class SignatureError < StandardError; end
# For each signature, a method of the same name in a module:
# it checks the arguments, calls the original with super, checks the result.
def enforce(klass, *lines, check: method(:type_ok?))
guard = Module.new
lines.each do |line|
name, params, ret = parse_sig(line)
guard.define_method(name) do |*args, &block|
where = "#{klass}##{name}"
unless args.size == params.size
raise SignatureError, "#{where}: expected #{params.size} arguments, got #{args.size}"
end
args.zip(params).each_with_index do |(arg, type), i|
next if check.(arg, type)
raise SignatureError, "#{where}: argument #{i + 1} should be #{type}, got #{arg.inspect}"
end
result = super(*args, &block)
unless ret == "void" || check.(result, ret)
raise SignatureError, "#{where}: should return #{ret}, returned #{result.inspect}"
end
result
end
end
klass.prepend(guard)
end
class CheckedShift < Shift
end
enforce(CheckedShift,
"def initialize: (String, Float) -> void",
"def cost: (Float) -> Float")
p CheckedShift.ancestors.first(3)
p CheckedShift.new("Bacon", 1.5).cost(80.0)
begin
CheckedShift.new("Bacon", "1.5")
rescue SignatureError => e
e.message
endThe anonymous module stands in front of CheckedShift. A correct call passes through unchanged, the wrong one is stopped at the door – with the place and the value in the message, where the first cell quietly made "1.51.51.51.5". enforce(Shift, ...) would guard Shift itself, and the check would stay installed for every later call, just as with rbs test.
A failed check does not always mean the code is wrong. Sometimes the signature is:
# A wrong signature is caught too: hours is a Float, not an Integer
class NightShift < Shift
end
enforce(NightShift, "def hours: () -> Integer")
begin
NightShift.new("Bacon", 1.5).hours
rescue SignatureError => e
e.message
endhours returns 1.5, the signature promised an Integer – here the code is right and the signature needs fixing. That is what such a test is for: it holds code and signatures against each other while your tests run. The real rbs does the same: RBS_TEST_TARGET names the classes, it wraps their methods (its docs describe Module#prepend; today's version renames the original with alias_method – the same idea) and raises RBS::Test::Tester::TypeError. It understands the whole language, unions, generics and blocks included, and it also checks the elements inside an Array.
You don't have to write every signature by hand: rbs prototype rb drafts them from a Ruby file (everything untyped), and TypeProf guesses real types from the code. Since RBS 4.0, signatures may also stand in the Ruby file itself, as comments – #: (Float) -> Float above a def, attr_reader :hours #: Float. That is still marked experimental; rbs --inline lib validate and Steep 2.0 read it.
$ rbs prototype rb lib/timesheet.rb # a first draft, all untyped $ gem install typeprof $ typeprof lib/timesheet.rb # guesses the types from the code $ rbs -I sig validate # is the .rbs itself sound? # rbs test: check every call while the tests run $ RBS_TEST_TARGET='Entry,Timesheet' RUBYOPT='-rrbs/test/setup' rake test [Entry#initialize] ArgumentTypeError: expected `::String` but given `830` # Steep: check the code against sig/ without running it $ gem install steep $ steep init # writes a Steepfile $ steep check
conforms?(value, type) below knows what type_ok? knows. Extend it: a value conforms to "Float | Integer" if it conforms to one of the parts, and to "String?" if it is nil or conforms to String. The two can meet: "Integer | String?". Then enforce can use it – enforce(SomeClass, "def bill: (Float, Float?) -> Float | nil", check: method(:conforms?)) – and the check tries exactly that.# type_ok? from above knows single types. RBS also writes
# String? - a String or nil
# Float | Integer - one of these
def conforms?(value, type)
# TODO: "A | B" - the value conforms to one of the parts
# TODO: "T?" - nil, or a value that conforms to T
case type
when "untyped" then true
when "bool" then value == true || value == false
when "nil" then value.nil?
else Object.const_get(type) === value
end
end
conforms?(nil, "String?")