Time, encodings and data formats

Data arrives with a time and an encoding. This part covers Time and Date, durations and time zones, parsing and formatting dates, and Unicode with the bytes and encodings behind it. The rest of the part reads and writes the formats a program exchanges: JSON, YAML, CSV, XML and HTML, and the configuration files built from them.

9.1 Encodings Trust UTF-8 by default, set magic comments, convert with encode, and scrub bad bytes. Open 9.2 Time and date Read the clock with Time.now, format with strftime, parse input, and do date math. Open 9.3 Time zones and durations A Time with an offset, utc against localtime, the monotonic clock for durations, and the difference between adding seconds and adding a calendar day. Open 9.4 Parsing and formatting dates Date.parse, Time.strptime with an explicit pattern, iso8601 and strftime, and the month arithmetic that is not thirty days. Open 9.5 Unicode, bytes and encodings bytesize against length, force_encoding on binary input, scrub to replace broken bytes, encode to another encoding, and the error a truncated UTF-8 file raises. Open 9.6 JSON and YAML Use the JSON stdlib to parse and generate data, and read config with Psych YAML. Open 9.7 CSV Read and write CSV files with the csv library, from plain rows to headers and converters. Open 9.8 YAML in depth safe_load and dump, anchors and aliases, the permitted classes that decide what a config may build, and why YAML is for config rather than for data on the wire. Open 9.9 CSV in depth CSV.generate and CSV.parse, headers and converters, writing and streaming a file, and the quoting rules that make a hand-built line wrong. Open 9.10 XML and HTML REXML for well-formed XML, attributes and XPath, why real HTML needs a forgiving parser, and when to add nokogiri. Open 9.11 Configuration files A YAML config read into a hash, defaults merged under it, environment variables on top, and a validation that stops the program before it does any work. Open

Lessons