Why does with_progress do "Thread.new"?

This code sets gems in your project based on the gem manifest. Why is it necessary to create threads for this?

module Gemifest
  class Installer
    def initialize(gem)
      @gem = gem
    end

    def perform!
      begin
        $stdout = StringIO.new('')
        $stderr = StringIO.new('')
        with_progress 'Installing ' + @gem.name do
          `#{@gem_command} install --no-ri --no-rdoc #{@gem.line}`
        end
      ensure
        $stderr = STDERR
        $stdout = STDOUT
      end
    end

    private

    def with_progress(label)
      STDERR.print label
      begin
        t = Thread.new do
          loop do
            STDERR.print('.')
            STDERR.flush
            sleep 0.8
          end
        end
        yield
        STDERR.puts ' done!' unless $?.exitstatus > 0
      rescue => e
        STDOUT.puts "Error:"
        STDOUT.puts e.message
      ensure
        t.kill
      end
    end
  end
end
+3
source share
1 answer

If you delete Thread.new, it yieldwill be executed after completion loop do ... end(i.e. never).

The goal of creating a loop in a separate thread is that it must be executed simultaneously with the block, and then be killed after the block is completed.

+3
source

Source: https://habr.com/ru/post/1717364/


All Articles