0
0
Ruby on Railsframework~5 mins

Asset pipeline basics in Ruby on Rails

Choose your learning style9 modes available
Introduction

The asset pipeline helps organize and prepare your website's images, styles, and scripts so they load fast and work well together.

When you want to combine many CSS or JavaScript files into one to speed up page loading.
When you need to compress images, CSS, or JavaScript to reduce file size for faster downloads.
When you want to write styles or scripts in newer languages like Sass or CoffeeScript and have them converted automatically.
When you want to add version numbers to assets so browsers know when to update them.
When you want to organize your assets in a clean folder structure inside your Rails app.
Syntax
Ruby on Rails
In Rails, assets like CSS, JS, and images go into app/assets, lib/assets, or vendor/assets folders.

Use manifest files like application.js or application.css to include other files:

//= require filename  (for JavaScript)
/*= require filename */   (for CSS)

Run 'rails assets:precompile' to prepare assets for production.

Manifest files list which assets to include and in what order.

Precompiling assets combines and compresses them for faster loading in production.

Examples
This JavaScript manifest includes jQuery, Rails UJS, and all other JS files in the folder.
Ruby on Rails
//= require jquery
//= require rails-ujs
//= require_tree .
This CSS manifest includes the styles in the file itself and all other CSS files in the folder.
Ruby on Rails
/*
 *= require_self
 *= require_tree .
 */
Using SCSS files lets you write easier and more powerful styles.
Ruby on Rails
app/assets/stylesheets/custom.scss

// You can write Sass here and it will be compiled to CSS automatically.
Sample Program

This example shows how to include a custom CSS and JS file in the main application manifests. When the app runs, the styles and scripts are combined and ready to use.

Ruby on Rails
/* app/assets/stylesheets/application.css */
/*
 *= require_self
 *= require custom
 */

/* app/assets/stylesheets/custom.css */
body {
  background-color: #f0f0f0;
}

// app/assets/javascripts/application.js
//= require rails-ujs
//= require custom

// app/assets/javascripts/custom.js
console.log('Hello from custom.js');
OutputSuccess
Important Notes

Always restart your Rails server after adding new assets to see changes.

Use 'rails assets:precompile' before deploying to production to optimize assets.

Keep your asset files organized to avoid confusion and make maintenance easier.

Summary

The asset pipeline organizes and prepares your CSS, JavaScript, and images for your Rails app.

It combines, compresses, and versions assets to make your website faster and easier to maintain.

Use manifest files to control which assets load and in what order.