Last Updated: February 25, 2016
·
3.11K
· joshwlewis

Rails scss/sass validator

I have an application where each client has their own custom styles (colors and header images mostly). So, each client has some scss snippets saved in the database. Instead of letting inproper formatting crash the precompiler, I validate it's format by just making sure Sass can compile it.

Create the validator:

<script src="https://gist.github.com/4113551.js?file=scss_format_validator.rb"></script>

# app/validators/scss_format_validator.rb
class ScssFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    begin
      # Attempt to parse SCSS
      Sass::Engine.new(value, syntax: :scss).render
    rescue Exception => e
      # Add error if parsing fails
      object.errors.add(attribute, :invalid_scss, error: e.inspect)
    end
  end
end

Then just add the validation call in the model:

validates :style_text, scss_format: true

View the Gist here.