Skip to content

Instantly share code, notes, and snippets.

@mipearson
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mipearson/9496903acc8be30d936b to your computer and use it in GitHub Desktop.
Save mipearson/9496903acc8be30d936b to your computer and use it in GitHub Desktop.
libsass/sassc working with Rails sprockets - rough impl, Rails 3.2
config.before_initialize do
require_relative '../lib/sassc_template'
Sprockets::Engines #force autoloading
Sprockets.register_engine '.scss', SasscTemplate
Sprockets.register_engine '.sass', SasscTemplate
end
require 'tilt/template'
require 'open3'
class SasscTemplate < Tilt::Template
self.default_mime_type = 'text/css'
class RenderError < StandardError
end
# Override Tilt::Template to insist on a file
def initialize(file=nil, line=1, options={}, &block)
@file, @line, @options = nil, 1, {}
[options, line, file].compact.each do |arg|
case
when arg.respond_to?(:to_str) ; @file = arg.to_str
when arg.respond_to?(:to_int) ; @line = arg.to_int
when arg.respond_to?(:to_hash) ; @options = arg.to_hash.dup
when arg.respond_to?(:path) ; @file = arg.path
else raise TypeError
end
end
raise ArgumentError, "file required, block not supported" if @file.nil?
prepare
end
def prepare
@load_paths = Rails.application.config.assets.paths.map(&:to_s)
end
def evaluate scope, locals, &block
stdout, stderr, s = Open3.capture3("sassc -l -t nested -I #{@load_paths.join(" -I ")} #{@file}")
if s.success?
depend_on_imports(scope, stdout)
stdout
else
raise SasscTemplate::RenderError, "\n\n#{stderr}"
end
end
def depend_on_imports scope, css
# Prune comments from the compiled SCSSand find our dependencies, so we can tell sprockets
# about them. If we don't, sprockets will not recompile if an import is changed.
regexp = %r{/\* line \d+, (.+css) \*/}
css.scan(regexp).sort.uniq.each do |file|
next unless file[0]
scope.depend_on(file[0])
end
end
def allows_script?
false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment