eagleeye eagleeye - 17 days ago 4x
Sass (Sass) Question

sprockets loads sass in random order with twitter bootstrap

What is the best way to enforce a certain order of sass sheets with twitter bootstrap? Reason is...

Sprockets random loading of sass and bootstrap is messing up me over riding certain css properties that bootstrap set like background color.

I want twitter bootstrap loaded first so I can over ride anything it sets.


Ok this method will load based on the order of imported files and will also only load the appropriate files based on the controller serving the pages. There are several things required to do this so I'll break them down.

First: Your going to remove the require_tree statement in your stylesheets/application.scss and your javascripts/application.js files.

Then, in your layouts/application.html.erb file you're going to add the following lines that will load the corresponding controller's stylesheets and javascripts:

Inside the head tag add:

<%=stylesheet_link_tag params[:controller] if Rails.application.assets_manifest.assets["#{params[:controller]}.css"] %>

Inside the body tag at the very bottom after your <%= yield %> statement you're going to add the following:

#The following line will load the controller related js files in your app/assets/javascripts folder as they're viewed.
<%= javascript_include_tag params[:controller] if Rails.application.assets_manifest.assets["#{params[:controller]}.js"] %>

#The following line will yield to any javascript wrapped in a `<%=content_for :javascript do %>` tag that you'll use at the bottom of the corresponding view page.  This is useful when you run some page related js and don't want it running application wide
<%=yield :javascript %>

Now in your config/initializers/assets.rb file you need to add any js or scss files to the precompilation array:

Rails.application.config.assets.precompile += %w( users.css users.js more_controller_named_files_or_anything_needing_loading_here )

Now on any view pages where you may have page specific js to run such as a DataTable you'd put the following at the bottom of your corresponding view:

<%=content_for :javascript do %> <!--This gets called in our layouts/application page! -->
      <script type='text/javascript'>
          $(document).ready(function() {
             whatever code here
   <% end %>

Then any css or js libraries that are site wide should go into your stylesheets/application.scss and javascripts/application.js files as follows:

    @import "bootstrap-sprockets";
    //blah blah blah

   //=require jquery
   // require whatever other files

Then you can use these import and require directives inside the controller named stylesheets and javascripts for more control on what library is loaded and when.  The asset pipeline can be intimidating at first but definitely worth while once you're familiar with it.