Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - How to pass Sprockets::Context in manual sass compiling

I'm using the following code snippet to manually compile a sass manifest with some variable overrides appended.

template = File.read("#{Rails.root}/app/assets/schemes/#{scheme}/css/styles.css.scss")

scheme_variables.each do |key, value|
  template << "$#{key}:#{value};\n"
end

engine = Sass::Engine.new(template, { 
  :syntax => :scss,
  :cache => false,
  :read_cache => false,
  :style => :compressed,
  :filesystem_importer => Sass::Rails::SassImporter,
  :load_paths => MyApp::Application.assets.paths,
  :sprockets => {
    :context => ?,
    :environment => MyApp::Application.assets
  }
})
output = engine.render

The Sass::Engine constructor wants a sprockets context and environment in the options hash. What do I put in for the context? The first thing I tried was...

:context => MyApp::Application.assets.context_class,

...but that gives me the following error "undefined method `font_path' for #" when it hits one of my sass asset helpers.

The second thing I tried was...

:context => ActionController::Base.helpers,

...That fixed the asset helper issue, but throws the following error "undefined method `depend_on' for #" when it tries to work through my glob imports (e.g. @import "mixins/*").

I'm using Rails 4.2 and sass-rails 5.0.3.

Any advice on this would be much appreciated. Thanks!

like image 910
ajporterfield Avatar asked Feb 10 '23 02:02

ajporterfield


1 Answers

With using Sass::Rails::ScssTemplate you can render your sass code with this snippet:

template = '...' # Your sass code

logical_path = pathname = ''
environment = Rails.application.assets
context = environment.context_class.new(environment, logical_path, pathname)

template = Sass::Rails::ScssTemplate.new(pathname) { template }
output = template.render(context, {})

If you want to render from a file then just add its path to pathname and its asset path to logical_path.

For me it works with Rails 4.2.5.1 and sass-rails 5.0.4.

like image 127
Timo Avatar answered Feb 24 '23 14:02

Timo