Skip to content

Instantly share code, notes, and snippets.

@lime
Created September 28, 2016 12:05
Show Gist options
  • Save lime/b0f9b0acba18387d60fe4e0f61acd41f to your computer and use it in GitHub Desktop.
Save lime/b0f9b0acba18387d60fe4e0f61acd41f to your computer and use it in GitHub Desktop.
Optional @import in sass / sass-rails
// ...
// -----------------------------------------------------------------------------
// Import JS generated CSS
// -----------------------------------------------------------------------------
@import "OPTIONAL:../javascripts/bundle/jscss/main";
@import "OPTIONAL:../javascripts/bundle/jscss/admin";
# config/initializers/sass_optional_import.rb
module OptionalImport
PREFIX = 'OPTIONAL:'.freeze
def find_relative(name, base, options)
if prefix?(name)
result = super(strip_prefix(name), base, options)
if result.nil?
Rails.logger.warn "Could not find optional import #{strip_prefix(name)}"
return Sass::Engine.new(dummy_sass(name), options)
end
return result
else
super
end
end
def find(name, options)
if prefix?(name)
result = super(strip_prefix(name), base, options)
if result.nil?
Rails.logger.warn "Could not find optional import #{strip_prefix(name)}"
return Sass::Engine.new(dummy_sass(name), options)
end
return result
else
super
end
end
def mtime(name, options)
if prefix?(name)
super(strip_prefix(name), options)
else
super
end
end
def key(name, options)
if prefix?(name)
super(strip_prefix(name), options)
else
super
end
end
def to_s
"#{self.class}(#{root})"
end
def eql?(other)
other.class == self.class && other.root == root
end
protected
def prefix?(name)
name.start_with?(PREFIX)
end
def strip_prefix(name)
name.start_with?(PREFIX) ? name[PREFIX.length..-1] : name
end
def dummy_sass(name)
".dummy-class-#{name.parameterize} { color: #F00F00 }"
end
end
module Sass
module Rails
class SassImporter
include OptionalImport
end
end
end
# Based heavily on:
# https://github.com/chriseppstein/sass-css-importer/blob/master/lib/sass/css_importer/importer.rb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment