Skip to content

Instantly share code, notes, and snippets.

@LucasBarretto86
Last active April 6, 2022 21:32
Show Gist options
  • Save LucasBarretto86/e1699059e596b7ebffb5b40ac6909d6b to your computer and use it in GitHub Desktop.
Save LucasBarretto86/e1699059e596b7ebffb5b40ac6909d6b to your computer and use it in GitHub Desktop.
Rails: Allowing local fonts in assets pipeline and allowing it on CORS

Allowing local fonts in assets pipeline and CORS

Adjusting assets.rb initializer to add fonts as part of pipeline

# /\.(?:svg|eot|woff|ttf)$/ to allow fonts to be precompiled to enabled it to be referenced by asset_path after CORS is allowed

Rails.application.config.assets.precompile  += %w(/\.(?:svg|eot|woff|ttf)$/) 

Rails.application.config.assets.paths << Rails.root.join('app', 'assets', 'fonts')

Install gem rack-cors

# Rails middleware
gem "rack-cors"

Adding Rack::Cors as middleware initializer

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '/assets/*', headers: :any, methods: [:get, :post, :patch, :put]
  end
end

How to call fonts on css.erb or html.erb

  @font-face {
    font-family: 'ValueSansPro';
    src: url(<%= asset_path('ValueSansPro-Regular.ttf') %>) format('truetype'),
    url(<%= asset_path('ValueSansPro-Regular.woff') %>) format('woff'),
    url(<%= asset_path('ValueSansPro-Regular.woff2') %>) format('woff2');
    font-weight: 300;
    font-style: normal;
  }

how to precompile assets to test locally

rails assets:precompile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment