Note: Checkout part one about web frameworks options in Crystal.
Once your Kemal app grows a little bit it seems obnoxious to declare tons of variables that are automatically passed down to the view.
Personally what I like to do when I’m feeling that the amount of variables is too damn high and the logic used inside the Kemal router is getting hard to reuse - is to introduce a presenter (simple class, no magic there) that basically wraps whole logic responsible for initializing variables I will need. And usually I drop-in some convenient helper methods.
To decouple it even further and make it a little bit more flexible I tend to implement decorators. If you use ecr
there is handy
def_to_s class method that allows you to specify template file to use when
to_s is called on your object. And it seems to me that it’s a perfect combination. The use case is as follows:
<!-- somewhere in static view we can just call --> <%- @movies.each_with_index do |movie, idx| -%> <%= Decorators::Movie.new(@presenter.category, movie, idx + 1) %> <% end %>
# src/decorators/movie.cr module Decorators class Movie @percentage : Int32 def initialize(@category : String, @movie : Mappings::Movie, @number : Int32) # here I calculate @percentage that I will later use as width of a progress bar end # inside that partial you will have access to all instance variables ECR.def_to_s "src/views/movies/_movie.ecr" end end
I think it’s a neat and convenient approach for building small static sites with Kemal.