ruby-on-railsasset-pipeline

Ruby on Rails - pass a `path` parameter to with asset host


I'm trying to get rails to load assets from a different domain with an additional path. For instance

I'm attempting to set up a CDN that would store different versions of a RoR app assets. We're using the asset pipeline and shakapacker to copy static assets to a public/assets/<static files> and public/packs/<js packs> directory.

I'd like to set up the CDN so that it the rails app can reference these assets by the version of the applicaiton that's running, for example:

/v1.2.3/packs/runtime.12345.js
/v2.2.3/assets/my-image.png

I tried setting config.asset_host = "cdn.url.com/v1.2.3/". This worked for the shakapacker assets but not the other files, like images, fonts, etc. The other files continued to load from the root directory, for example, here's the urls that it generated:

With regards to the missing assets - it seems that they are incorrect due to issues with the compiled scss url()'s. For example, the output of the css compilation step gives theseurls:

background:url(/assets/home/hero/hero-2560x300@2x-736e9b0d2d9b52ded1dc31f75c7905f4141115b9a02322efd3b5304a7b860c2b.jpg)

Now the scss compilation happens using dart-sass rails. We're also using shakapacker so that may be involved.

I also tried setting config.assets.prefix = "/v1.2.3" which resulted in a broken application - the application couldn't find the files locally.

Is what I'm trying to do possible?


Solution

  • To solve this problem of hosting assets on a cdn in side a subdirectory, here's what I found out:

    1. before building, set environment variable RAILS_RELATIVE_URL_ROOT=/prefix

    This sets the build prefix for the css so that all the paths are prefixed with the specified path.

    1. Build assets bundle exec rake assets:precompile --trace

    2. Upload public/* to the cdn

    3. On the production application host, set environment variable ASSET_HOST=https://cdn.url.com/prefix