Transitioning to HAML
21 Jan 2015Well I finally experimented with haml. Surprisingly, it felt relatively easy transitioning from html files (embedded with erb) to haml files.
As the documentation suggests:
Give yourself 5 minutes to read the tutorial and then convert one of your ERB templates to Haml. Simplify. Enjoy. Laugh. 20 minutes later, you will never go back.
So that’s exactly what I did with my guitar forum website. Here’s one of the views displaying list of guitars before and after using haml (note I did some additional refactoring which I’ll explain below):
###Before (html + erb)
###After (haml)
How does that look? I think it’s much easier to read.
While I was converting form erb to haml, I also noticed that there was a bit of
presentation logic that could be taken out of the views. I used a
decorator pattern (another blog post) to get some of the presentation logic out of the view. In addition, I
noticed that @posts
could also be extracted out into its own partial,
and rails has its own convention we can use with haml: = render @posts
.
These two changes really helped to make the new files much cleaner.
Afer getting comfortable with haml, you don’t have to manually convert your old files from erb to haml. Check out the html2haml gem, or you can also use this website to convert individual pages.
Rewriting some of my views in haml was fun and invigorating. I recommend at least taking a stab at it in one of your small projects.