2016-12-30 1 views
8

code 문자열에는 코드 조각이 저장되어 있으며 CSS, SASS, SCSS, JavaScript 또는 CoffeeScript가 될 수 있습니다. 콘텐츠는 사용자가 제공하고 데이터베이스에 저장하기 전에 구문을 확인해야합니다.레일 : CSS 또는 JS 코드 코드를 문자열에서 확인하는 방법은 무엇입니까?

구문이 올바른지 확인해야합니다. 현재, 나는 작동하는 못생긴 해킹을 사용하고 있습니다. 더 나은 해결책이 있습니까?

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 
+0

나는 더 나은 해결책을 찾기 위해 어디에서 이것을 호출하고 왜 이것이 필요한지를 알아 보는 것이 유용 할 것이라고 생각합니다. –

+1

내게 잘 어울린다 –

+0

@ Caffeinated.tech 제안에 감사드립니다.이 구를 추가했습니다.이 내용이 더 명확 해지기를 바랍니다. "사용자가 콘텐츠를 가져오고 있으며, satabase에 저장하기 전에 구문을 검증해야합니다." – Benj

답변

-1
# 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

관련 문제