Class: Progress::WithProgress

Inherits:
Delegator
  • Object
show all
Includes:
Enumerable
Defined in:
lib/progress/with_progress.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enumerable, title, length = nil, &block) ⇒ WithProgress

initialize with object responding to each, title and optional length if block is provided, it is passed to each



12
13
14
15
16
# File 'lib/progress/with_progress.rb', line 12

def initialize(enumerable, title, length = nil, &block)
  super(enumerable)
  @enumerable, @title, @length = enumerable, title, length
  each(&block) if block
end

Instance Attribute Details

#enumerableObject (readonly)

Returns the value of attribute enumerable.



8
9
10
# File 'lib/progress/with_progress.rb', line 8

def enumerable
  @enumerable
end

#titleObject (readonly)

Returns the value of attribute title.



8
9
10
# File 'lib/progress/with_progress.rb', line 8

def title
  @title
end

Instance Method Details

#eachObject

each object with progress



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/progress/with_progress.rb', line 19

def each
  enumerable = case
  when @length
    @enumerable
  when
        @enumerable.is_a?(String),
        @enumerable.is_a?(IO),
        Object.const_defined?(:StringIO) && @enumerable.is_a?(StringIO),
        Object.const_defined?(:TempFile) && @enumerable.is_a?(TempFile)
    warn "Progress: collecting elements for instance of class #{@enumerable.class}"
    @enumerable.each.to_a
  else
    @enumerable
  end

  length = case
  when @length
    @length
  when enumerable.respond_to?(:size)
    enumerable.size
  when enumerable.respond_to?(:length)
    enumerable.length
  else
    enumerable.count
  end

  Progress.start(@title, length) do
    enumerable.each do |object|
      Progress.step do
        yield object
      end
    end
    @enumerable
  end
end

#in_threads(*args, &block) ⇒ Object

befriend with in_threads gem



61
62
63
64
65
# File 'lib/progress/with_progress.rb', line 61

def in_threads(*args, &block)
  @enumerable.in_threads(*args).with_progress(@title, @length, &block)
rescue
  super
end

#with_progress(title = nil, length = nil, &block) ⇒ Object

returns self but changes title



56
57
58
# File 'lib/progress/with_progress.rb', line 56

def with_progress(title = nil, length = nil, &block)
  self.class.new(@enumerable, title, length || @length, &block)
end