-
-
Save Dagnan/175168c456629a4ad1acdba8e0cdedb9 to your computer and use it in GitHub Desktop.
Inline CSS or JS in Rails 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<%= inline_js 'application.js' %> | |
<%= inline_css 'application.css' %> | |
</head> | |
<body> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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]))
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
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.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.