Rails: how to check CSS or JS code from a string?

In the code line, I saved a piece of code, maybe CSS, SASS, SCSS, JavaScript or CoffeeScript. The content comes from the user, and I need to check the syntax before saving to the database.

I need to check the syntax is correct. I am currently using an ugly hack that works. Do you have a better solution?

 def check_js if language == 'coffee' # CoffeeScript CoffeeScript.compile code else # JavaScript Uglifier.compile code end rescue ExecJS::RuntimeError => e errors.add :code, e.message end def check_css if language == 'css' # CSS Sass::CSS.new(code).render else # SASS, SCSS Sass.compile code, syntax: language.to_sym end rescue Sass::SyntaxError => e errors.add :code, e.message end 
+9
ruby-on-rails sass coffeescript
source share
2 answers
 # app/models/user.rb class User < ActiveRecord::Base validates_with Validators::SyntaxValidator end # app/models/validators/syntax_validator.rb class Validators::SyntaxValidator < ActiveModel::Validator def validate(record) @record = record case language when :coffee CoffeeScript.compile(code) when :javascript Uglifier.compile(code) when :css Sass::CSS.new(code).render when :sass Sass.compile code, syntax: language.to_sym when :scss Sass.compile code, syntax: language.to_sym end rescue Sass::SyntaxError => e errors.add :code, e.message rescue ExecJS::RuntimeError => e errors.add :code, e.message end end 

Maybe something like this? What do you think? http://api.rubyonrails.org/classes/ActiveModel/Validator.html

+1
source share

Using Sass :: CSS.new gave me an uninitialized persistent Sass :: CSS error, although I have sass and sass-rails gems installed. So I found another gem.

https://github.com/w3c-validators/w3c_validators

 include W3CValidators validator = CSSValidator.new results = validator.validate_text(css_code) if results.errors.length > 0 @success = false results.errors.each do |err| puts err.to_s end else @success = true end 
0
source share

All Articles