2

I want to run sass from within Ruby script. Compiling a scss file scss can be done by doing:

require "sass"
Sass::Engine.new(File.read(scss), options).render

with some appropriate hash assigned to options, but I want to compile it only if scss or any of its partial (imported) files if updated.

Within options, I have sass caching turned on. Caching keeps all the update information of the relevant files in a certain directory. I feel that, by doing up to:

engine = Sass::Engine.new(File.read(scss), options)

there must be information available in engine by which I can tell if scss or any of its partial files is updated. Only in such case, I should run:

engine.render

to do the compiling. How can I detect the file update based on the sass cache?

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    If you just want to compile your `scss` files when they're changed, you can look into something like [guard-sass](https://github.com/hawx/guard-sass). – Josh Voigts Oct 02 '13 at 13:38
  • I don't want to run it as a deamon. I want to do it from within a Ruby code, as I wrote in my question. – sawa Oct 02 '13 at 17:20

1 Answers1

0

You can use:

Sass::Engine.for_file(scss, options).render

This will check whether there is a cached parse tree in the cache directory for the scss file hash. See the documentation for Sass::Engine.for_file here: http://sass-lang.com/docs/yardoc/Sass/Engine.html.

The cache lookup is performed in the Sass::Engine#_to_tree method, source code available here: https://github.com/nex3/sass/blob/stable/lib/sass/engine.rb.

EDIT

First few lines of Sass::Engine#_to_tree:

def _to_tree
  if (@options[:cache] || @options[:read_cache]) &&
      @options[:filename] && @options[:importer]
    key = sassc_key
    sha = Digest::SHA1.hexdigest(@template)

    if root = @options[:cache_store].retrieve(key, sha)
      root.options = @options
      return root
    end
  end
  # ...
end
Jacob Brown
  • 7,221
  • 4
  • 30
  • 50
  • As you can tell if you actually read the source code of `Sass::Engine.for_file`, which I did before asking, all it does is call `Sass::Engine.new(File.read(filename), options.merge(:filename => filename))`, which is essentially the same as what I wrote in the question. – sawa Oct 03 '13 at 02:42
  • You did not pass the `:filename` option in your example. If you will read the `Sass::Engine#_to_tree` source, which is called as part of `render`, you can see where the cache lookup happens. – Jacob Brown Oct 03 '13 at 11:10
  • I did not write what I have in `options`, but I have `:filename` specified in `options`. – sawa Oct 03 '13 at 11:16