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
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.
# 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With