Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Inline CSS or JS in Rails 5
<!DOCTYPE html>
<html>
<head>
<%= inline_js 'application.js' %>
<%= inline_css 'application.css' %>
</head>
<body>
</body>
</html>
module AssetsHelper
def inline_file(path)
if assets = Rails.application.assets
asset = assets.find_asset(path)
return '' unless asset
asset.source
else
File.read(File.join(Rails.root, 'public', asset_path(path)))
end
end
def inline_js(path)
"<script>#{inline_file path}</script>".html_safe
end
def inline_css(path)
"<style>#{inline_file path}</style>".html_safe
end
end
@humphreybc
Copy link

humphreybc commented Oct 18, 2017

It looks like this doesn't work in when running in production. The ‘else’ block gets called, and results in this error. It looks like asset_path(path) is returning the full URL.

ActionView::Template::Error: No such file or directory @ rb_sysopen - /app/public/https://stg.dovetailapp.com/assets/website-03a6f92b281f277642a029db4b0a3a65bdd196e6d9d4eee8d4f5b95782863ca4.css

Edit: Looks like the problem was caused by this line in our production.rb config file. Will leave this comment here for other people in case they have a similar issue.

config.action_controller.asset_host = 'https://' + Figaro.env.domain

@vishwakarma
Copy link

vishwakarma commented Sep 24, 2018

You may use below if you have asset hosts configured as cdn
path = "Your asset name", like - home.css
File.read(File.join(Rails.root, 'public', 'assets', Rails.application.assets_manifest.assets[path]))

@julianguyen
Copy link

julianguyen commented Sep 26, 2018

Thanks for this! Does it work for scss?

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