compass-sass

Compass / Sass check if file exists


I'm using compass to generate sprites and a have a mixin that calculates the width and height of the original asset and adds that into the css.

I also have an option on this mixin to pass in true or false for hover state images. But rather than having to specify this each time I use the mixin I'd like to add the hover css by default if the file exists.

I've added the following to my config.rb file (thus far its the only extension I have)

module Sass::Script::Functions
  def file_exists(image_file)
    path = image_file.value
    Sass::Script::Bool.new(File.exists?(path))
  end
end

And my mixin looks like this

@mixin sprite($name, $hover: true, $active: false, $pad:0){
    @include sprite-dimensions($sprites, $name);
    background-repeat: no-repeat;
    background-image: sprite-url($sprites);
    background-position: sprite-position($sprites, $name, -$pad, -$pad);

    @if $hover == true{
        $name_hover: $name + _hover;
        @if file_exists($name_hover){
            &:hover {
                background-position: sprite-position($sprites, $name_hover, -$pad, -$pad);
            }
        }
    }

}

But the file_exists function doesn't return true; presumably because the path to the file is incorrect. What / How do i specify the correct path?


Solution

  • I managed to find a solution, that, rather than checking if the file exists, it checks the sprite map that is created (from all the files that definitely exist)

    I changed

    @if file_exists($name_hover){
    

    to

    @if sprite_has_selector($sprites, $name, hover){