繁体   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