Rails:如何从字符串中检查CSS或JS代码?

时间:2016-12-30 12:58:41

标签: ruby-on-rails sass coffeescript

code字符串中,我存储了一段代码,可以是CSS,SASS,SCSS,JavaScript或CoffeeScript。 内容来自用户,我需要在保存到数据库之前验证语法。

我需要检查语法是否正确。目前,我正在使用一个有效的丑陋黑客。你有更好的解决方案吗?

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

2 个答案:

答案 0 :(得分:0)

# 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

也许是这样的?你认为呢? http://api.rubyonrails.org/classes/ActiveModel/Validator.html

答案 1 :(得分:0)

使用Sass :: CSS.new给了我一个未初始化的常量Sass :: CSS错误,即使我安装了sass和sass-rails 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