Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 880
Benj Avatar asked Dec 30 '16 12:12

Benj


People also ask

How do you know if the code is CSS or HTML?

Press "Ctrl-F" and type "style." The window searches the code for that word. If you see a style tag in an HTML document, that document uses CSS. The code between the opening <style> tag and the closing </style> tag contains the CSS.


1 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 you think? http://api.rubyonrails.org/classes/ActiveModel/Validator.html

like image 98
dmitriy_strukov Avatar answered Oct 16 '22 00:10

dmitriy_strukov