How to Create Sprite Images using Compass Rails Gem in Rails 4.2.5

Steps

Step 1

Create a new rails project.

Step 2

Copy icons to app/assets/images/icons folder.

Step 3

Create a sprites folder in app/assets/images folder

Step 4

Add gem compass-rails to Gemfile. Run:

bundle

Step 5

Rename application.css to application.scss.

Step 6

Create your resource.

rails g scaffold article title:string content:text

Step 7

Add, the following to app/assets/stylesheets/articles.scss file.

@import "compass/utilities/sprites";
@import "icons/*.png";
@include all-icons-sprites;

Read the compass gem home page to learn more about these declarations.

Step 8

In production.rb, enable assets and configure the folder where the generated sprite images should be stored.

config.assets.enabled = true
config.compass.generated_images_dir = app/assets/images/sprites

You can also add it to development.rb for testing locally in development environment.

Step 9

Run:

rake assets:precompile

Step 10

You will see the generated sprite file in app/assets/images/sprites folder. Add app/assets/images/sprites/* to .gitignore file.

Sample source code can be downloaded from https://github.com/bparanj/rcompass.

Summary

In this article, you learned how to use compass-rails gem to generate sprite images for Rails 4.2.5 apps. It reduces the number of files to download from a server and therefore improves the performance.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.