tags:

views:

30

answers:

1

I have this code

if filename
  begin
    if filename == '-'
      ARGF.each{|url|
        begin
          check(url)
        rescue Timeout::Error, Errno::ETIMEDOUT
          puts "Timeout Error, try again"
          redo
        end
      }
    else
      File.open(filename) {|file|
        file.each{|url|
          begin
            check(url)
          rescue Timeout::Error, Errno::ETIMEDOUT
            puts "Timeout Error, try again"
            redo
          end
        }
      }
    end
  rescue Interrupt, Errno::EINTR
    exit(1)
  end
end

But I don't want repeated code for stdin and file, how can I rewrite it?

+2  A: 

You can pull out your repeated code into a method and call that on ARGF or file as they respond to the same methods.

def do_check(to_check)
  to_check.each do |url|
    begin
      check(url)
    rescue Timeout::Error, Errno::ETIMEDOUT
      puts "Timeout Error, try again"
      redo
    end
  end
end

Then your example becomes:

if filename
  begin
    if filename == '-'
      do_check(ARGF)    
    else
      File.open(filename) do |file|
        do_check(file)
      end
    end
  rescue Interrupt, Errno::EINTR
    exit(1)
  end
end

I've used do ... end rather than {} simply because I find it easier to read.

Shadwell