Module: Enumerable

Defined in:
lib/mb/core_ext/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#concurrent_map(method_name = nil, *args, &block) ⇒ Array Also known as: concurrent_collect

Map across all members using Celluloid futures, and wait for the results.

This chooses the best behavior based on each item, and whether a method and argument list or block are passed.

Examples:

Passing a method and arguments


[1, 2, 3].concurrent_map(:next)
# => [2, 3, 4]

[1, 2, 3].concurrent_map(:modulo, 2)
# => [1, 0, 1]

Passing a block


[1, 2, 3].concurrent_map { |n| n + 1 }
# => [2, 3, 4]

Parameters:

  • method_name (Symbol) (defaults to: nil)

    The name of the method to call on each item in the collection

  • args (Array)

    The argument list, if any, to pass to each method send

  • block (Proc)

    A block to yield each item to

Returns:

  • (Array)

    a new array containing the values returned by the futures



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mb/core_ext/enumerable.rb', line 28

def concurrent_map(method_name = nil, *args, &block)
  futures = if method_name
    map { |item|
      if item.respond_to?(:future)
        item.future(method_name, *args)
      else
        Celluloid::Future.new { item.send(method_name, *args) }
      end
    }
  elsif block_given?
    map { |item|
      Celluloid::Future.new { block.yield item }
    }
  else
    raise ArgumentError, "Requires method and argument list, or a block"
  end

  futures.map(&:value)
end