加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:18:27 所属栏目:百科 来源:网络整理
导读:在代码字符串中我存储了一段代码,可以是CSS,SASS,SCSS,JavaScript或CoffeeScript. 内容来自用户,我需要在保存到数据库之前验证语法. 我需要检查语法是否正确.目前,我正在使用一个有效的丑陋黑客.你有更好的解决方案吗? def check_js if language == 'coffee
在代码字符串中我存储了一段代码,可以是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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读