Converting ERB to Slim

I looked around and there was seemingly no easy way to convert Rails apps to use Slim instead of ERB. There was a gem out there, but it didn’t seem to work for me.

The general process I used was to first convert ERB to Haml using Haml’s haml2html. Next, convert Haml to Slim using haml2slim.

Convert ERB to Haml

Ensure you have Haml installed, preferably using your Gemfile if using Bundler. You can probably remove Haml when you are done with this process.

I got much inspiration from this article on the conversion process.

# to test what you will convert
find . -name '*html.erb' | \
xargs ruby -e 'ARGV.each { |i| puts "html2haml -r #{i} #{i.sub(/erb$/,"haml")}"}'

# to convert
find . -name '*html.erb' | \
xargs ruby -e 'ARGV.each { |i| puts "html2haml -r #{i} #{i.sub(/erb$/,"haml")}"}' | bash

Somewhere in this process the whitespace gets mostly stripped out. This is unfortunate, but should take less time overall to fix than converting over by hand.

Then, assuming you are using version control (not sure how much longer I will believe that this is not universal), remove the .erb files.

rm -rf "**/*.html.erb" # works in zsh at least...

This is important because Rails will look at your *.erb files first, so if you don’t delete them then the results of running html2haml won’t be seen.

Fix anything that is broken. In my case it was some illegal nesting and bad indentation problems in a couple of partials, as well as some other things that needed to be changed.

Look through the app in the browser if your tests don’t cover all of the views and for a sanity check. You may have to restart your server if you installed Haml.

Convert Haml to Slim

Ensure you have Slim installed, preferably using your Gemfile if using Bundler. Run gem install haml2slim (we don’t need this in the Gemfile since it’s for one-time use not in the application.)

Slim template files have the ending extension .slim, like their counterparts ERB (.erb) and Haml (.haml).

Again, we use a converter.

find . -name '*html.haml' | xargs ruby -e 'ARGV.each { |i| puts "haml2slim #{i} #{i.sub(/haml$/,"slim")}"}' | bash

Again, we delete the extra files (*/.html.haml this time).

Again, we fix anything that is broken.

Now hopefully your app should be fully converted to use Slim! Suddenly a puppy appears and the sun comes out from behind the clouds.

Categories: development

« Bundler see what updates are available Rails Raw SQL Insert -- Time Wrong »