Moving forward in a for loop despite an error

76 views Asked by At

I have this code:

require 'octokit'
require 'csv'

client = Octokit::Client.new :login => 'github_username', :password => 'github_password'
repo = 'rubinius/rubinius'
numbers = CSV.read('/Users/Name/Downloads/numbers.csv').flatten
# at this point, essentially numbers = [642, 630, 623, 643, 626]

CSV.open('results.csv', 'w') do |csv|
     for number in numbers
         begin
          pull = client.pull_request(repo, number)
          csv << [pull.number, pull.additions, pull.deletions]
         rescue
          next
        end
     end    
  end

However, at times the client.pull_request encounters a 404 and then jumps over and goes to the next. However, it still needs to print the number in the numbers array, and then put a blank or zero for pull.additions and pull.deletions and then move on to the next item in the array, thus producing something like:

pull.number pull.additions pull.deletions
642,        12,            3
630,          , 
623,        15,            23
...

How can this be done?

2

There are 2 answers

0
bjhaid On BEST ANSWER

I have removed the for loop as it is not rubyish in nature, the below should work

require 'octokit'
require 'csv'

client = Octokit::Client.new :login => 'github_username', :password => 'github_password'
repo = 'rubinius/rubinius'
numbers = CSV.read('/Users/Name/Downloads/numbers.csv').flatten
# at this point, essentially numbers = [642, 630, 623, 643, 626]

CSV.open('results.csv', 'w') do |csv|
     numbers.each do |number|
         begin
          pull = client.pull_request(repo, number)
          csv << [pull.number, pull.additions, pull.deletions]
         rescue
          csv << [0,0,0]
          next
        end
     end    
  end
0
Justin On

Have you tried using a begin/rescue/ensure such that the rescue/ensure code will set the pull variable appropriately? See https://stackoverflow.com/a/2192010/832648 for examples.