簡體   English   中英

Ruby on Rails:使用上傳的文件“實時”處理CSS Lint和JS Lint

[英]Ruby on Rails: Processing CSS Lint and JS Lint “realtime” with uploaded files

我們的應用程序允許用戶上傳javascript,CSS和HTML文件。 我們需要一種方法來根據CSS和JS lint驗證這些文件,並記錄與它們相關的任何錯誤(文件名,行等)。 這需要“實時”完成,或者至少要傳遞到延遲的工作流程中才能在后台工作。 這些要求不允許我們加入第三方在線服務(例如在線w3c驗證器)。

我找到了jshint_on_rails和jslint_on_rails,看來它們可以工作。 但是,它們依賴於rake任務,而且我不確定如何將其輸出存儲到數據庫中。 到目前為止,我還沒有找到關於CSS Lint的類似信息。 是否有類似這樣的軟件包可供我掛接?

謝謝

我最終要做的是安裝JSHint和CSSLint的Node.js版本,然后通過Rails調用它們並解析輸出,如下所示:

  def validate_js(filepath)
    capture_error = false
    filename = get_filename(filepath)
    file_regex = Regexp.new(filepath)
    lint_config = "--config #{Rails.root}/test/validators/jshint.json"
    lint_reporter = "--reporter #{Rails.root}/test/validators/jshint-reporter.js"

    IO.popen("jshint #{filepath} #{lint_config} #{lint_reporter}") do |pipe|

      pipe.each do |line|
        if line =~ file_regex
          # Error detected
          error_msg = line.split("#{filepath}: ").last.strip
          @js_error = @instance.parse_warnings.new(:filename => filename, :error_type => 'javascript', 
                                                        :error_message => error_msg)
          capture_error = true
        elsif capture_error 
          # The actual line the error is on
          @js_error.error_content = line
          @js_error.save!

          capture_error = false
          @js_error = nil # Empty the variable so it isn't hanging around after the last error
        end
      end
    end
  end



def validate_css(filepath)
    filename = get_filename(filepath)
    dir = File.expand_path(File.dirname(filepath)) # Where we want to dump the results.xml file

    system("csslint --format=lint-xml > #{dir}/#{filename}-results.xml #{filepath}") # Call CSSLint

    output = LibXML::XML::Parser.file("#{dir}/#{filename}-results.xml")
    doc = output.parse # Iterate over the errors
    doc.find('//issue').each do |issue|
      error_msg = "line #{issue['line']}, col #{issue['char']}, #{issue['reason']}"
      error_content = issue['evidence']
      @instance.parse_warnings.create!(:filename => filename, :error_type => 'css', :error_message => error_msg,
                                            :error_content => error_content)
    end
    FileUtils.rm("#{dir}/#{filename}-results.xml") # No need to keep the xml file around
  end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM