Skip to content

Instantly share code, notes, and snippets.

@samanthamjohn
Created February 17, 2012 14:42
Show Gist options
  • Save samanthamjohn/1853859 to your computer and use it in GitHub Desktop.
Save samanthamjohn/1853859 to your computer and use it in GitHub Desktop.
Configuring the an automatic sprite generator with the Rails 3.1 asset pipeline

This is a useful shortcut to getting up and running with the excellent but slightly out-of-date Sprite Gem from gistinc https://github.com/gistinc/sprite.

Your file tree should look something like:

app/assets/images/sprites/{name_of_sprite_folder}/{source_png_images}

Running

rake sprite

will first generate a sprite image named {name_of_sprite_folder}.png. Unfortunately the way the asset pipeline works means that images in app/assets/images need to be referenced as "assets/{image_name}" in your css file in order to link up properly. What this means is that in order for your sprite generator to generate the correct file paths you need to add:

image_output_path: assets/sprites/

to your config file. This means that the sass file will generate correct code but also that the png file it generates will be saved to the wrong directory.

This is why the second step of the rake task moves the generated sprite png into the app/assets/images/sprites/ folder so that it can be served correctly from the correct folder.

I have it set up to use sass_mixin which means you will generate a _sprite.sass file that can be mixed in to your other stylesheets with:

@import 'sprite.sass';

You can then add a sprite background image to any class simply by adding:

@include sprite("{name_of_sprite_folder}", "{name_of_original_image}");
task :sprite do
`sprite` && `mv app/assets/assets/sprites/*.png app/assets/images/sprites/`
end
config:
style: sass_mixin
public_path: app/assets/
image_output_path: assets/sprites/
sprites_class: 'sprites'
class_separator: '-'
default_format: png
style_output_path: stylesheets/application/_sprites
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment