Last Updated: February 25, 2016
·
954
· gus

Using SASS functions

CSS-preprocessors are amazing, anyone denying that hasn't dealt with servers or hasn't written enough css. For example, when dealing with multiple applications with different code bases being routed by a reverse proxy server you may found yourself being limited by sass-rails's asset helpers, as the path generated inside your css files do not reflect the same dynamism as the ones in your markup.

SASS comes with a bunch of nifty things out of the box, one of them are functions. You can declare your customized functions in an initializer and pass Ruby specific logic into your CSS, how cool is that?

For instance, if for whatever reason we want to create a different asset path for our images depending on the environment we are in, we can do so implementing a SASS function.

require 'sass'

module Sass::Script::Functions
  def environment
    Sass::Script::String.new(Rails.env)
  end
end

Then you can use this function in your SCSS in whatever way you see fit, for instance:

$images_root: "/assets/";

@if environment() == "staging"
  $images_root: "/routed-application-url/assets/";

@else if environment() == "production"
  $images_root: "/routed-application-url-2/assets/";