timelog becomes persistent
So far our entries live only in memory. Time for serialization: turning data into text and back. Ruby ships the three most important formats. JSON is the language of web APIs:
require "json"
entries = [
{ project: "ProjectX", hours: 3.5 },
{ project: "Intern", hours: 2.0 }
]
text = JSON.pretty_generate(entries)
puts text
JSON.parse(text, symbolize_names: true) == entriesNote symbolize_names: true – JSON has no symbols, so keys would come back as strings otherwise. CSV is the format for tables (Excel!):
require "csv"
csv_text = CSV.generate do |csv|
csv << ["project", "hours"]
entries.each { |e| csv << [e[:project], e[:hours]] }
end
puts csv_text
CSV.parse(csv_text, headers: true).map { |row| row["project"] }And YAML is the favorite for configuration files – pleasant for humans to read and write:
require "yaml"
config = YAML.safe_load("rate: 120\nround_to: 15\n")
config["rate"]And now: files! On your machine Ruby saves with File.write and reads with File.read. Here in the browser we simulate a little filesystem for that – with its own file window (show_files):
File.write("notizen.txt", "buy bacon!\ntest timelog.")
File.write("projekte/plan.txt", "Q4: finish timelog")
show_filesClick a file to peek inside – just like Explorer or Finder. And everything else works as usual: reading, searching, checking:
[File.read("notizen.txt"),
Dir.glob("**/*.txt"),
File.exist?("beispiel.csv")]Our file window is a simulation – on your machine these are real files on disk, with the same commands. There you also get extra comfort:
# Block form closes the file automatically:
File.open("log.txt", "a") { |f| f.puts "new entry" }
Pathname.new("a/b.json") # paths as objects
Tempfile.create("test") # throwaway files for tests
StringIO.new("...") # in-memory "file"to_csv(entries) (CSV text with header project,hours) and from_csv(text) (back to hashes with symbol keys and Float hours). Then save data with File.write into entries.csv and read it back with from_csv(File.read(…)) – losslessly. Afterwards take a look at the file window above (⟳)!require "csv"
data = [
{ project: "A", hours: 1.5 },
{ project: "B", hours: 2.0 }
]
# def to_csv(entries)
# ...
# end
# def from_csv(text)
# ... # hint: row["hours"].to_f
# end
# File.write("entries.csv", to_csv(data))
# from_csv(File.read("entries.csv"))