我最終什麼事做的是安裝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