Question

Background

I have a directory of images, app/assets/images/sprites/flags/*.png that will be sprited. Compass, Sass, and Sprockets work together such that I can put

@import "sprites/flags/*.png";
...
.flag.en {
  @include flags-sprite(en)
}

in my .scss file. By doing so, Compass generates the file app/assets/images/sprites/flags-abc123.png when I compile SCSS files.

Problem

I would like to precompile that flags-abc123.png file via a Rake task or shell command without compiling my .scss file. Is there a way to do so?

Rationale

Compiling all of the .scss files in the application is a lengthy part of the deploy process. We would like to speed up deploys by generating them on one machine and distributing them. Unfortunately, the other machines generate bad cache-busting URLs because they are missing the compiled sprite files. If we can precompile the sprite files, we can speed up deploys dramatically.

What I tried

I tried running bundle exec compass sprite app/assets/images/sprites/flags/*.png. That generates app/assets/stylesheets/_flags.scss, but doesn't generate app/assets/images/sprites/flags-abc123.png.

Était-ce utile?

La solution

I ended up making a Rake task:

class SpriteTask
  include Rake::DSL

  attr_reader :file_task

  def initialize(glob)
    @glob = glob
    build_compass_sprite_map
    define_task
  end

  private

  attr_reader :glob, :map

  def build_compass_sprite_map
    uri = Sass::Script::String.new(glob)
    context = Object.new
    kwargs = {}
    kwargs.extend Compass::SassExtensions::Functions::Sprites::VariableReader
    @map = Compass::SassExtensions::Sprites::SpriteMap.from_uri uri, context, kwargs
    @map.options = {}
  end

  def define_task
    @file_task = file(map.filename => map.image_filenames) do |task|
      map.generate
    end
  end
end

and using it like so:

require 'sprite_task'
namespace :sprites do
  task :generate do
    SpriteTask.new('foo/*.png').file_task.invoke
    SpriteTask.new('bar/*.png').file_task.invoke
  end
end
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top