Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downside to serving fonts from /public directory in Rails?

I love the asset pipeline but for the life of me I cannot get it to serve my fonts. I wasted hours googling and trying SO solutions (nope, nope, nope).

Instead I created /public/fonts, dropped all my fonts in there and reference them with url('/fonts/myAwesomeFont.ttf'). Everything works perfectly.

Is there a downside to this approach?

Are font files compressed in asset pre-compilation?

like image 704
RSG Avatar asked Feb 29 '12 19:02

RSG


1 Answers

We keep our fonts in the /app/assets/fonts folder and to my recollection we did not have to do any additional configuration.

You do however have to use the asset_path helper in your CSS files when you reference the fonts (same as when referencing asset pipeline images in CSS). This requires changing your file extension from .css to .css.erb. It's hard to tell for certain from your description but I'm guessing that may be the problem.


Example

We use the Museo500 font in our app and store it in app/assets/fonts:

app/assets/fonts:
  - museo700-regular-webfont.eot
  - museo700-regular-webfont.woff
  - museo700-regular-webfont.ttf
  - museo700-regular-webfont.svg

The @font-face declaration is as follows:

@font-face {
    font-family: 'Museo700';
    src: url('<%= asset_path "museo700-regular-webfont.eot" %>');
    src: url('<%= asset_path "museo700-regular-webfont.eot" %>?#iefix') format('embedded-opentype'),
         url('<%= asset_path "museo700-regular-webfont.woff" %>') format('woff'),
         url('<%= asset_path "museo700-regular-webfont.ttf" %>') format('truetype'),
         url('<%= asset_path "museo700-regular-webfont.svg" %>#Museo700') format('svg');
    font-weight: normal;
    font-style: normal;

}


Benefits of using asset pipeline for binary files

We don't do any kind of precompilation for image or font assets (I guess you could gzip the fonts or something but we don't) but I still see a benefit to hosting them through the asset pipeline: uniformity and convention. With Rails convention can offer all kinds of benefits.

Ex: At some point you may want to use a CDN like Amazon Cloudfront and will need to make all your asset urls in production point to the CDN copies. If you're hosting all your assets including fonts and images through the asset pipeline that change is as easy changing the asset_host in your production.rb file by uncommenting the lines:

  # Enable serving of images, stylesheets, and JavaScripts from an asset server
  # config.action_controller.asset_host = "http://assets.example.com"

If you're already referencing your fonts with the asset_path helper then those urls will be updated automatically to point to the CDN. I guess it's as much a benefit of using path_helpers as the asset pipeline itself, but either way it's beneficial.

Hope this helps!

like image 185
jshkol Avatar answered Oct 28 '22 01:10

jshkol