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.
Written by Josh Lewis
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Sass
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#