ruby-on-rails – Rails:如何从字符串中检查CSS或JS代码?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails:如何从字符串中检查CSS或JS代码?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
代码字符串中我存储了一段代码,可以是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

解决方法

# 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

猜你在找的Ruby相关文章