Tutto insieme: l'interfaccia web
Per concludere colleghiamo tutto: le collezioni per il report, Roda per il routing, ERB come linguaggio di template e il mini browser come palcoscenico. ERB è HTML con Ruby incorporato: <%= … %> inserisce un valore, <% … %> esegue codice (cicli!):
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) dà al template accesso alle variabili locali della route – è così che report arriva nell'HTML. Le view in Rails, Sinatra e Roda funzionano esattamente così (con in più qualche comodo helper attorno).
r.get "project", String do |name| … end: mostra una pagina di dettaglio con il nome del progetto come titolo e tutti i valori di ore del progetto (per es. con map/join). I percorsi sconosciuti restano 404. Con questo timelog è completo – fai un giro tra le pagine!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, "/"
🎓 Ce l'hai fatta!
Hai costruito timelog dalla prima collezione fino a un'interfaccia web – con test, gestione degli errori, il tuo DSL e la metaprogrammazione. Non sono conoscenze da giocattolo: proprio questi mattoni si trovano in ogni vero progetto Ruby.
E adesso? Esercitati con i Ruby Koans, ricostruisci timelog sul tuo computer come gem vera e propria (la lezione 117 ne mostra la struttura) – e se vuoi approfondire: i libri Programming Ruby (“il Pickaxe”) e Polished Ruby Programming ti portano dal mestiere alla maestria. E tutto ciò che dimentichi strada facendo lo trovi nel e nella documentazione di Ruby (lezione 48). CHUNKY BACON! 🦊🥓