Use variable defined in config.rb in scss files Use variable defined in config.rb in scss files ruby ruby

Use variable defined in config.rb in scss files


In your config.rb file add a custom module:

module Sass::Script::Functions  def custom_color(value)    rgb = options[:custom][:custom_colors][value.to_s].scan(/^#?(..?)(..?)(..?)$/).first.map {|a| a.ljust(2, a).to_i(16)}    Sass::Script::Color.new(rgb)  endend

And then set up your variables (again, in the config.rb file):

sass_options = {:custom => { :custom_colors => {"main" => "#ff1122"} } }

Then in your scss file, you can use the custom_color() function:

body {  background-color: custom_color(main);}

You could also write another custom function which returns other types such as font sizes, measurements, etc. by passing in strings, and then returning the appropriate class instance.

Interestingly, this would allow you to pass in environment variables into the compass command line, and that would generate different results.

So if you sass_options are:

sass_options = {:custom => { :custom_colors => {"main" => ENV["MAIN_COLOR"]} } }

And you run compass:

MAIN_COLOR=#dd1122 bundle exec compass compile

Then whatever color you pass in on the command line will appear in the resultant css. If you're using Heroku, you could heroku config:set MAIN_COLOR=#224411 and be able to set template colors on a per-app basis, using the same scss files.