kshep92
kshep92

Reputation: 895

Rail Asset Pipeline and Page Specific Files

In my rails 3.1 app, I have specific files that are to be loaded for each action in each controller e.g. users#index requires and index.js and index.css file while users#show requires a show.js and show.css file etc.

However, when I run rake assets:precompile, everything gets mushed into one big application.css and application.js file and it's messing up my views big time. Is there a way, aside from doing the "config.assets.precompile += %w(index.js show.css)" way to avoid this behaviour when using rake assets:precompile? Do I have to structure and name my files differently?

Upvotes: 1

Views: 342

Answers (2)

kshep92
kshep92

Reputation: 895

I solved the problem by applying proper scopes in my CSS and JavaScript. E.g. my layout file's body tag is given a dynamic id in the following manner:

<body id="<%= "#{params[:controller]}-#{params[:action]}" %>" data-controller=<%= params[:controller] %> data-action=<%= params[:action] %>>

And in my users_index.css file, that action is scoped and styled using:

body#users-index { .. }

My CSS manifest thus looks like this:

/*
 *= require self
 *= require jqueryUi
 *= require_tree .
*/

As for JavaScript, I do the following:

APP = { init: function() { ... }, 
        users = { 
                  index: function() { 
                           //jQuery bindings here; 
                  }, 
                  show: function() {  
                        //More jQuery bindings here for this action;
                  }
         } 
       }

Now, when the page loads, I do the following:

(function() {
    action = $("body").data("action");
    controller = $("body").data("controller");
    APP.init();
    APP[controller][action]();
          })();

A bit of a workaround, but I saw Paul Irish and his buddies do the JavaScript thing and I saw Ryan Bates from RailsCasts do the CSS method so I suppose it can't be 100% bad practice.

Upvotes: 2

Richard Hulse
Richard Hulse

Reputation: 10493

At a guess I would say that the order the files are included is messing things up.

What you will generally want is any boilerplate code first in your mamisfest, then your own site-wide sheets, and then lastly the action sheets.

So your application.css might look like this:

/*
 *= require reset
 *= require formtastic
 *= require jquery-ui
 *= require formtastic_overrides
 *= require site
 *= require_tree . 
*/

The other thing that might be messing this up is applying broad rules (e.g. p{color:green}) in an associated file, and expecting that to be served for just that action.

That isn't how the pipeline works, and you'll need to apply more specific rules for those views if that is what you are trying to achieve.

Personally, I don't use all those generated files. I prefer to put my CSS in a few files so I can see it in (mostly) one place. I find that easier to manage but YMMV!

Upvotes: 0

Related Questions