简体   繁体   中英

Can I use CSS assets and the public folder in the same app?

I have a legacy application that I'd like to migrate to use the Rails 3 asset pipeline. I have upwards of 100 stylesheets which are imported on a template by template basis using a

content_for :stylesheets

block.

Compiling them all into a single stylesheet is not currently a goer as the code was written to expect only certain stylesheets on certain pages, so for example the login page imports a stylesheet which redefines article form . It would not be good to redefine this on all pages.

Is there a way to migrate slowly to the assets pipeline having the app look first for a compiled asset , and then having it failover to the public/stylesheets directory?

If you want to do this "right", one thing that would not take a huge amount of effort would be to put a class name on your <html> or <body> tag and wrap the contents of your CSS files with a selector. For example, I use something similar to the following in my ApplicationController .

before_filter :body_class

def body_class
  controller_name = self.class.name.gsub(/Controller$/, '')
  if !controller_name.index('::').nil?
    namespace, controller_name = controller_name.split('::')
  end

  @body_classes = ["#{controller_name.underscore}_#{action_name} ".downcase.strip]
  @body_classes = ["#{namespace.underscore}_#{@default_body_classes.join}".strip] if !namespace.nil?
end

Then, in my layout I have something similar to this

<body class="<%= @default_body_classes.join(' ') %>">

Next, you could change the extension for all of your stylesheets to .css.scss . Put them all in the new app/assets/stylesheets directory. To include them quickly (though possibly out of order) , add

/*
 * =require_tree .
 */

to the top of a new app/assets/application.css.scss file. Just include this one application.css file in your layouts.

<%= stylesheet_link_tag "application", :media => 'screen' %>

Finally, spend some time going through your stylesheets wrapping the entirety of each document with the appropriate body class. For example, if you have a stylesheet specific to some User::Admin controller's signup action, you would wrap the entirety of that stylesheet with

.user_admin.signup {
  /* Your stylesheet's content here */
}

Sass will prefix all nested content properly with the .user_admin.signup class that will be appended to your <body> tag when that action's being rendered.

I realize this isn't really an intermediate fix as you're looking for, but following steps similar to this you should be able to get 95% of the way there with not much effort, and it will be done "right".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM