class TumblrSync::Runner

Public Class Methods

new(arguments) click to toggle source
# File lib/tumblr-sync/runner.rb, line 8
def initialize(arguments)
  @options = OptionParser.new
  @arguments = arguments
end

Public Instance Methods

run() click to toggle source
# File lib/tumblr-sync/runner.rb, line 13
def run
  parse_options!

  tumblr = TumblrSync::Tumblr.new @arguments.last
  progress_bar = ProgressBar.create format: '%a |%B| %c/%C - %p%%', starting_at: 0, total: tumblr.total
  photo_fetcher = PhotoFetcher.new tumblr.host

  FileUtils.mkdir_p tumblr.host

  queue = Queue.new
  tumblr.times do |i|
    Thread.new { queue << tumblr.images(i*MAX, MAX) }
  end

  downloader = Thread.new do
    tumblr.times do
      images = queue.pop
      images.each_slice(10).each do |group|
        threads = []
        group.each do |urls|
          progress_bar.total += (urls.size - 1)
          urls.each do |url|
            threads << Thread.new {
              begin
                photo_fetcher.fetch url
              rescue Mechanize::ResponseCodeError
              ensure
                progress_bar.increment
              end
            }
          end
        end
        threads.each(&:join)
      end
    end
  end

  downloader.join
rescue SocketError
  puts "Tumblr API not found!"
  puts @options
  exit
end

Private Instance Methods

parse_options!() click to toggle source
# File lib/tumblr-sync/runner.rb, line 59
def parse_options!
  @options.banner = "Usage: #{$0} [tumblr]"
  @options.on('-h', '--help', "Show this message") { puts(@options); exit }
  begin
    raise "Missing argument tumblr url" if @arguments.empty?
    @options.parse! @arguments
  rescue => ex
    puts ex.message
    puts @options
    exit
  end
end