I dont want to use *= require_tree. in application.css so that page
specific css will remain separate to each other.
In that case, why don't you include the file in your layout
directly:
<%= stylesheet_link_tag 'application', 'main', :media => "all",'data-turbolinks-track' => true %>
This will allow you to include the CSS file separately, both in development & production.
Of course, this recommendation is discounting the naming & file extension issues that you have:
Precompile
In the production environment Sprockets uses the fingerprinting scheme
outlined above. By default Rails assumes assets have been precompiled
and will be served as static assets by your web server.
You mention you want to keep your file separate from other CSS. require_tree
is exactly the same as require
-- it calls a file to be included in your application.css
file.
There is nothing wrong with this, except if you want to include the files separately, you'll want to ensure you keep them separate. To do this, you should assign the main
to your precompilation array:
#config/application.rb
config.assets.precompile += ["main.css"]
This means that when you run your application in production, you'll be able to use the main.css
file independent of any other.
--
Name
Finally, and probably most poignantly, you'll need to make sure you call only one file main
. The reason is that regardless of whether you use css
, erb
or scss
, the file will always be transformed into a css
file
This means if you have multiple files with the same name, Rails will become confused (as you've discovered). To remedy this, you have to ensure you're able to name the files you need individually
--
Preprocessor
Finally, as mentioned by Sampriti Panda
, you should opt to use scss
preprocessor over erb
in your asset pipeline. The main reason for this is that the preprocessor allows you to precompile the assets with impunity
I'd change your erb
file to this:
#app/assets/stylesheets/main.css.scss
.your_element {
background-image: asset_url('data.png');
}
This will work both as a dynamic and static file