Class: InThreads

Inherits:
Delegator
  • Object
show all
Defined in:
lib/in_threads.rb,
lib/in_threads/filler.rb,
lib/in_threads/thread_limiter.rb

Defined Under Namespace

Classes: Filler, ThreadLimiter

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enumerable, thread_count = 10, &block) ⇒ InThreads

Returns a new instance of InThreads.



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/in_threads.rb', line 6

def initialize(enumerable, thread_count = 10, &block)
  super(enumerable)
  @enumerable, @thread_count = enumerable, thread_count.to_i
  unless enumerable.is_a?(Enumerable)
    raise ArgumentError.new('`enumerable` should include Enumerable.')
  end
  if thread_count < 2
    raise ArgumentError.new('`thread_count` can\'t be less than 2.')
  end
  each(&block) if block
end

Instance Attribute Details

#enumerableObject (readonly)

Returns the value of attribute enumerable.



5
6
7
# File 'lib/in_threads.rb', line 5

def enumerable
  @enumerable
end

#thread_countObject (readonly)

Returns the value of attribute thread_count.



5
6
7
# File 'lib/in_threads.rb', line 5

def thread_count
  @thread_count
end

Class Method Details

.use(runner, options) ⇒ Object

Specify runner to use

use :run_in_threads_consecutive, :for => %w[all? any? none? one?]

:for is required :ignore_undefined ignores methods which are not present in Enumerable.instance_methods



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/in_threads.rb', line 30

def use(runner, options)
  methods = Array(options[:for])
  raise 'no methods provided using :for option' if methods.empty?
  ignore_undefined = options[:ignore_undefined]
  enumerable_methods = Enumerable.instance_methods.map(&:to_s)
  methods.each do |method|
    unless ignore_undefined && !enumerable_methods.include?(method)
      class_eval <<-RUBY
        def #{method}(*args, &block)
          #{runner}(enumerable, :#{method}, *args, &block)
        end
      RUBY
    end
  end
end

Instance Method Details

#grep(*args, &block) ⇒ Object

Special case method, works by applying run_in_threads_consecutive with map on enumerable returned by blockless run



75
76
77
78
79
80
81
# File 'lib/in_threads.rb', line 75

def grep(*args, &block)
  if block
    run_in_threads_consecutive(enumerable.grep(*args), :map, &block)
  else
    enumerable.grep(*args)
  end
end

#in_threads(thread_count = 10, &block) ⇒ Object

Creates new instance using underlying enumerable and new thread_count



19
20
21
# File 'lib/in_threads.rb', line 19

def in_threads(thread_count = 10, &block)
  self.class.new(enumerable, thread_count, &block)
end

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

befriend with progress gem



84
85
86
# File 'lib/in_threads.rb', line 84

def with_progress(title = nil, length = nil, &block)
  ::Progress::WithProgress.new(self, title, length, &block)
end