The Custom Asset Pipeline (CAP) is a powerful tool designed to streamline the process of managing and delivering assets in a web application. Whether you are dealing with images, stylesheets, JavaScript files, or other resources, CAP provides a flexible and efficient way to organize and optimize your assets.

Overview

CAP is built on top of the existing asset pipeline provided by Ruby on Rails, and it extends its capabilities to offer a more customized and flexible solution. Here are some key features of CAP:

  • Asset Caching: Leverages HTTP caching headers to reduce load times and improve performance.
  • Asset Minification: Automatically minifies JavaScript and CSS files to reduce file size.
  • Asset Compression: Compresses assets to further reduce load times.
  • Asset Versioning: Ensures that assets are always up-to-date by appending a version number to the file name.
  • Custom Asset Paths: Allows you to specify custom paths for your assets.

Getting Started

To get started with CAP, you first need to install it as a gem in your Rails application. You can do this by adding the following line to your Gemfile:

gem 'custom_asset_pipeline'

After installing the gem, run bundle install to install the dependencies.

Next, you need to configure CAP in your Rails application. To do this, add the following line to your config/application.rb file:

require 'custom_asset_pipeline'

Once you have configured CAP, you can start using it to manage your assets.

Usage

Here are some examples of how to use CAP in your Rails application:

Adding Assets

To add a new asset to your application, simply create a new file in the appropriate directory (e.g., app/assets/stylesheets/ for stylesheets, app/assets/javascripts/ for JavaScript files, etc.).

For example, to add a new stylesheet, you can create a file named example.css in the app/assets/stylesheets/ directory.

body {
  background-color: #f0f0f0;
}

To include this stylesheet in your layout, use the stylesheet_link_tag helper method:

<%= stylesheet_link_tag 'example' %>

Minification and Compression

CAP automatically minifies and compresses your assets. To customize this behavior, you can add the following lines to your config/initializers/custom_asset_pipeline.rb file:

CustomAssetPipeline.config do |config|
  config.minify = true
  config.compress = true
end

Asset Versioning

CAP automatically appends a version number to the file name of your assets. This ensures that your assets are always up-to-date.

For example, if you have a file named example.css, it will be versioned as example-<version>.css, where <version> is a unique identifier for the asset.

Resources

For more information on CAP, please visit the following resources:

Rails Asset Pipeline