How to Implement Custom Fonts in Rails
Walk through a step by step process for including custom fonts inside a Ruby on Rails application.
Guide Tasks
  • Read Tutorial

Our application may be shaping up, however it is bothering me that fonts aren't matching the designer's mock. This is not only an issue of fixing an annoyance, difference fonts can effect spacing and alignment so it's good to utilize the correct font relatively early. And that's what we're going to do in this guide.

We already copied over everything that we need for this to work, let's list out what needs to change:

  • The template/fonts.css file needs to be changed so it will allow for embedded Ruby so that it can access the Rails asset pipeline
  • We'll then need to update the font file with calls to where the fonts are located inside of the application, namely app/assets/stylesheets/fonts/
  • Lastly we'll need to update the template/main.css.erb file so it calls the correct font file

Convert CSS File to Accept ERB

We can do this easily by renaming the file:

mv app/assets/stylesheets/template/fonts.css app/assets/stylesheets/template/fonts.css.erb

This will give us the ability to create a direct connection between the file and the asset pipeline. I typically prefer this method over trying to call the files manually.

Update the file with the correct Rails asset pipeline calls

When you open up app/assets/stylesheets/template/fonts.css.erb you'll see that there are dozens of calls to the fonts/ directory. There is some busywork involved in changing these, essentially they all need to be changed to the format:

url(<%= '../fonts/MuseoSans-300Italic.eot' %>);

So go through and make all of the changes, I'll include a link at the bottom of this section if you want to copy and paste it.

Update the Main CSS File

Lastly it will probably be a good idea to update the main.css.erb file so that it's calling the correct path for the fonts since there are probably a few places where the designer is calling new fonts (that we may or may not run into later). Let's update the top font call here:

/* app/assets/stylesheets/template/main.css.erb */

@import "fonts.css";

Now if you startup the rails server and navigate to a page such as the Topic page you'll see that the new fonts are loading properly:

large

And if you click on one of the posts you'll see that the Post page is looking much better with the correct fonts:

large

So that wasn't too difficult, the key to integrating custom fonts in Rails is to simply know where they are in the asset pipeline so that you can call them directly. Next we'll work on implementing a design for the homepage.

Resources