queenofgoats queenofgoats - 2 months ago 26
Sass (Sass) Question

Using fonts with Rails 4.2.4

I'm trying to use a particular font in a Rails 4.2.4 app and nothing is working--it stubbornly refuses to show up. I've spent a few hours on it, and I don't know what I'm doing wrong.

The font is located at

app/assets/fonts/comic_andy.tff
.

SCSS (located at
app/assets/stylesheets/sass/application.css.scss
):

@font-face {
font-family: "comic_andy";
src: font-url('comic_andy.ttf');
src: font-url('comic_andy.ttf'), format('truetype');
}


In the browser, the SCSS compiles to this CSS:

@font-face {
font-family: "comic_andy";
src: url(/fonts/comic_andy.ttf);
src: url(/fonts/comic_andy.ttf), format("truetype");
}


Isn't it supposed to be compiling to assets/comic_andy.ttf? I'm newer to Rails and although I get what the asset pipeline is, it's still proving tricky to wrap my head around enough to use very efficiently.

I've read through Rails 4 - Custom Fonts, How to use fonts in Rails 4 and several other Stack Overflow questions related to fonts/Rails/the asset pipeline, and tried many of the suggestions, including (but not limited to!) adding
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
to
application.rb
(nope), trying
asset-url
(nope),
font-url
(nope), and plain
url
(nope), and restarting the server several times after
rake assets:clobber
(nope). :(

Answer

Don't change the assets path

If you put your resources into app/assets, you're all set, as mentioned here.

The default locations are: the images, javascripts and stylesheets directories under the app/assets folder, but these subdirectories are not special - any path under assets/* will be searched.

Use asset-url or font-url

If you refer to The Asset Pipeline page on Ruby on Rails guides, you'll see the adequate method here is to use asset-url (or font-url) as in:

@font-face {
    font-family: 'comic_andy';
    src: asset-url('comic_andy.ttf') format('truetype');
}

On your development environment, it should compile as:

@font-face {
    font-family: 'comic_andy';
    src: url(/assets/comic_andy.ttf) format("truetype");
}

NB: the proper format for .ttf files is format("truetype").

Make sure your font format is supported

If things still don't work, maybe there's a problem with your ttf file (my project is using the woff format) and you should maybe use a service such as Font Squirrel Webfont generator to fix it.