Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Joshua Briley
PLUS
Joshua Briley
Courses Plus Student 24,645 Points

I use scssify in Jekyll to inline "critical css" in the head of my document. Is there something similar for Rails?

In Jekyll projects, I use the scssify filter to inline styles in the following manner:

<style>{% capture include_to_sassify %}{% include css/main.scss %}{% endcapture %}{{ include_to_sassify | scssify }}</style>

More background information can be found here, if you're interested: https://medium.com/design-open/becoming-a-jekyll-god-ef722e93f771#.9jl3ozoxz

I tried the approach listed here: https://gist.github.com/averyvery/6e4576023b395de1aaf5

In application.rb

config.assets.precompile += ['critial.css', 'theme.js', 'application.js']

In incline_css_helper.rb

module InlineCssHelper
  # Inline CSS and JS as needed
  def read_file_contents(stylesheet)
    if %w(test development).include?(Rails.env.to_s)
      # if we're running the full asset pipeline,
      # just grab the body of the final output
      stylesheet.source
    else
      # in a production-like environment, read the
      # fingerprinted and compiled file
      File.read(File.join(Rails.root, 'public', 'assets', stylesheet.digest_path))
    end
  end

  def inline_file(asset_path)
    begin      
      file = Rails.application.assets.find_asset(asset_path)
      file.nil? ? '' : read_file_contents(file)
    rescue => ex
      ex.message
    end
  end

  def inline_js(asset_path)
    "<script>#{inline_file asset_path}</script>"
  end

  def inline_css(asset_path)
    "<style>#{inline_file asset_path}</style>"
  end
end

This approach seems to work fine in local dev, but it fails on staging. If there is a pre-existing gem that can help accomplish, I'd love to try it. Does anyone have any recommendations?

Joshua Briley
Joshua Briley
Courses Plus Student 24,645 Points

Found my issue... This solution works... when you actually precompile the appropriate file.

This: critical.css

config.assets.precompile += ['critial.css', 'theme.js', 'application.js']

Should have been: critical_css.css

config.assets.precompile += ['critial_css.css*', 'theme.js', 'application.js']

Rookie mistake. :-)