Everything together: the web interface
To finish, we connect everything: collections for the report, Roda for routing, ERB as the template language and the mini browser as the stage. ERB is HTML with embedded Ruby: <%= … %> inserts a value, <% … %> runs code (loops!):
install_gem "roda"
require "roda"
require "erb"
ENTRIES = [
{ project: "ProjectX", hours: 3.5 },
{ project: "Intern", hours: 2.0 },
{ project: "ProjectX", hours: 3.0 }
]
TEMPLATE = ERB.new(<<~HTML)
<h1>timelog</h1>
<table border='1' cellpadding='6'>
<tr><th>Project</th><th>Hours</th></tr>
<% report.each do |project, hours| %>
<tr>
<td><a href='/project/<%= project %>'><%= project %></a></td>
<td><%= hours %></td>
</tr>
<% end %>
</table>
HTML
class TimelogWeb < Roda
route do |r|
r.root do
report = ENTRIES.group_by { |e| e[:project] }
.transform_values { |l| l.sum { |e| e[:hours] } }
TEMPLATE.result(binding)
end
end
end
show_browser TimelogWeb, "/"TEMPLATE.result(binding) gives the template access to the route's local variables – that's how report reaches the HTML. Views in Rails, Sinatra and Roda work exactly like this (with comfort helpers wrapped around).
r.get "project", String do |name| … end: it shows a detail page with the project name as heading and all the project's hour values (e.g. via map/join). Unknown paths stay 404. With that, timelog is complete – click around!install_gem "roda"
require "roda"
require "erb"
ENTRIES = [
{ project: "ProjectX", hours: 3.5 },
{ project: "Intern", hours: 2.0 },
{ project: "ProjectX", hours: 3.0 }
]
class TimelogWeb < Roda
route do |r|
r.root do
"<h1>timelog</h1><a href='/project/ProjectX'>ProjectX</a> <a href='/project/Intern'>Intern</a>"
end
# r.get "project", String do |name|
# matching = ENTRIES.select { ... }
# "<h2>...</h2>..."
# end
end
end
show_browser TimelogWeb, "/"
🎓 You made it!
You built timelog from the first collection to a web interface – with tests, error handling, your own DSL and metaprogramming. That's not toy knowledge: exactly these building blocks sit inside every real Ruby project.
Where next? Practice with the Ruby Koans, rebuild timelog on your own machine as a proper gem (lesson 117 shows the structure) – and if you want to dig deeper: the books Programming Ruby (“the Pickaxe”) and Polished Ruby Programming take you from craft to mastery. And whatever you forget along the way is on the and in the Ruby docs (lesson 48). CHUNKY BACON! 🦊🥓