Sunday, January 8, 2017

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

Leave a Comment

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 

2 Answers

Answers 1

I don't see the code in the question as a hack.

I think if you want something that can really run in the browser, test it in a browser.

Ruby has two excellent ways to run browsers to evaluate code, Capybara and PhantomJS.

Answers 2

Nokogiri is an HTML, XML, SAX, and Reader parser. Among Nokogiri's many features is the ability to search documents via XPath or CSS3 selectors.

Features

  • XML/HTML DOM parser which handles broken HTML
  • XML/HTML SAX parser
  • XML/HTML Push parser
  • XPath 1.0 support for document searching
  • CSS3 selector support for document searching
  • XML/HTML builder
  • XSLT transformer

Nokogiri parses and searches XML/HTML using native libraries (either C or Java, depending on your Ruby), which means it's fast and standards-compliant.

Refer Nokogiri

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment