简体   繁体   中英

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

In a code string I have stored a piece of code, can be CSS, SASS, SCSS, JavaScript or CoffeeScript. The content is coming from the user, and I need to validate the syntax before saving in the database.

I need to check if the syntax is correct. Currently, I'm 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
# 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 you think? http://api.rubyonrails.org/classes/ActiveModel/Validator.html

Using the Sass gem will throw uninitialized constant Sass::CSS error, so instead you can use its parser directly:

Sass::SCSS::Parser.new(code, nil, nil).parse;

this will return an error if the CSS code has any syntax errors

Using Sass::CSS.new gave me an uninitialized constant Sass::CSS error even though I have the sass and sass-rails gems installed. So I found a different 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM