4

I want to capture the total number of rubocop offenses to determine whether my codebase is getting better or worse. I have almost no experience with ruby scripting.

This is my script so far:

#!/usr/bin/env ruby
#script/code_coverage

var = `rubocop ../ -f fuubar -o ../coverage/rubocop_results.txt -f offenses`
puts var

So I ./rails-app/script/code_coverage and my terminal displays

...
--
6844  Total

When I var.inspect I get a long string. I want to either read the output of rubocop ../ -f ... line by line (preferred) or capture each line of output into an array.

I would like to be able to do something like this:

var.each |line| do
  if line.contains('total')
    ...
    total = ...
end

Is this possible? I guess this would be similar to writing the output to a file and and then reading the file in line by line.

2 Answers 2

5

If you want to keep it simple, you can simply split your var string.

var = `rubocop ../ -f fuubar -o ../coverage/rubocop_results.txt -f offenses`.split("\n")

Then you can iterate on var like you wanted to.

Sign up to request clarification or add additional context in comments.

Comments

2

use open3 library of ruby. Open3 grants you access to stdin, stdout, stderr and a thread to wait the child process when running another program. You can specify various attributes, redirections, current directory, etc., of the program as Process.spawn.

http://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html

require 'open3'


# Run lynx on this file.
cmd = "lynx -crawl -dump /data/feed/#{file_name}.html  > /data/feed/#{file_name}"
Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|
   cmdout = stdout.read
   $logger.debug "stdout is:" + stdout.read
   $logger.debug "stderr is:" + stderr.read
end

2 Comments

what is $logger.debug?
instance of a ruby gem called lumberjack. I would recommend you to check it out if you are trying to log anything. github.com/bdurand/lumberjack

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.