0

How can I make some asset files (.js and .css) from my rails app available to another site?

Example:

// allow this to be added to some external website
<link rel="stylesheet" href="https://myrailsapp.com/external/mystyle.css">
<script src="https://myrailsapp.com/external/myscript.js"></script>

The js and css files should be compiled by the standard asset pipeline.

1 Answer 1

1

For rails 5 add the desired assets to be precompiled in config/initializers/assets.rb

Rails.application.config.assets.precompile += %w( external/myscript.js external/mystyle.css )

This will generate a precompiled version of your assets on each deploy.

With digest (default rails behavior, recommended)

There is a problem with appended digest though. Precompiled assets will be named something like

mystyle-36050fdf64ed881b967d4216084ed3072da6369f1b4dcf783ea28435f6db0091.css

You can alter your deployment setup to run a rake task that will remove the digest from the asset's filename. For example https://github.com/galetahub/ckeditor/blob/master/lib/tasks/ckeditor.rake

Let's say you are using capistrano to deploy your application. You have to add something like this to config/deploy.rb

namespace :deploy do
  after :restart, 'your_rake_task_namespace:task_name'
end

Without digest (simpler but hurts cache invalidation)

If you don't want to add complexity to your deploy setup just disable assets fingerprinting. Do it globaly by adding config.assets.digest = false in config/application.rb or for a single environment config/environments/production.rb

Sign up to request clarification or add additional context in comments.

4 Comments

I hesitate to add the extra complexity of removing the digest. I'd prefer dynamic creation with a fixed route unless performance turns out to be prohibitive.
I have updated my answer, you can disable the digest by adding config.assets.digest = false to config/application.rb
@de. it does, the only difference is that in rails 4 there is no config/initilizers/assets.rb so you have to add config.assets.precompile += ['your-asset.js'] to config/application.rb
You already helped me a lot, I have the logical follow-up question about cache-control: stackoverflow.com/q/59887924/921573 Would you share some more insights?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.