0
0
Ruby on Railsframework~5 mins

Sprockets asset pipeline in Ruby on Rails

Choose your learning style9 modes available
Introduction

The Sprockets asset pipeline helps organize and prepare your website's CSS, JavaScript, and images so they load faster 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 or minify your styles and scripts to reduce file size.
When you want to use special features like writing CSS with variables or JavaScript with modules.
When you want to manage images and fonts easily in your Rails app.
When you want to automatically update assets when you change their source files.
Syntax
Ruby on Rails
//= require filename
// This directive includes another JavaScript or CSS file into the current one.

Use //= require in JavaScript or CSS manifest files to include other files.

Files are processed and combined in the order of these directives.

Examples
This includes the jQuery library first, then includes all files in the current directory.
Ruby on Rails
//= require jquery
//= require_tree .
In CSS, require_self includes the current file's styles before adding styles from custom.css.
Ruby on Rails
/*
 *= require_self
 *= require custom
 */
Sample Program

This example shows how to use Sprockets directives in CSS and JavaScript files. The CSS manifest includes its own styles and then the custom styles. The JavaScript manifest includes jQuery and all other JS files in the folder. When the app runs, 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 jquery
//= require_tree .

// app/assets/javascripts/custom.js
console.log('Custom JS loaded');
OutputSuccess
Important Notes

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

Use rake assets:precompile to prepare assets for production.

Sprockets processes files in the order you specify, so order matters.

Summary

Sprockets helps combine and prepare CSS, JavaScript, and images for your Rails app.

Use //= require and *= require directives to include files.

This makes your app faster and easier to manage.