Sha256: 3aef1dbe3fe768de06bbb36aae289ce713c131a55b83f1d1aa92ab78f45bc66d

Contents?: true

Size: 1.36 KB

Versions: 15

Compression:

Stored size: 1.36 KB

Contents

module Enumerable
  # 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.
  #
  # @param [Symbol] method_name
  #   The name of the method to call on each item in the collection
  # @param [Array] args
  #   The argument list, if any, to pass to each method send
  # @param [Proc] block
  #   A block to yield each item to
  #
  # @example Passing a method and arguments
  #
  #   [1, 2, 3].concurrent_map(:next)
  #   # => [2, 3, 4]
  #
  #   [1, 2, 3].concurrent_map(:modulo, 2)
  #   # => [1, 0, 1]
  #
  # @example Passing a block
  #
  #   [1, 2, 3].concurrent_map { |n| n + 1 }
  #   # => [2, 3, 4]
  #
  # @return [Array] a new array containing the values returned by the futures
  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
  alias_method :concurrent_collect, :concurrent_map
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
motherbrain-1.5.0 lib/mb/core_ext/enumerable.rb
motherbrain-1.4.0 lib/mb/core_ext/enumerable.rb
motherbrain-1.3.0 lib/mb/core_ext/enumerable.rb
motherbrain-1.2.1 lib/mb/core_ext/enumerable.rb
motherbrain-1.2.0 lib/mb/core_ext/enumerable.rb
motherbrain-1.1.3 lib/mb/core_ext/enumerable.rb
motherbrain-1.1.2 lib/mb/core_ext/enumerable.rb
motherbrain-1.1.1 lib/mb/core_ext/enumerable.rb
motherbrain-1.1.0 lib/mb/core_ext/enumerable.rb
motherbrain-1.0.0 lib/mb/core_ext/enumerable.rb
motherbrain-0.14.5 lib/mb/core_ext/enumerable.rb
motherbrain-0.14.4 lib/mb/core_ext/enumerable.rb
motherbrain-0.14.3 lib/mb/core_ext/enumerable.rb
motherbrain-0.14.2 lib/mb/core_ext/enumerable.rb
motherbrain-0.13.1 lib/mb/core_ext/enumerable.rb