Class: Export::FileGrouper

Inherits:
Object
  • Object
show all
Defined in:
lib/export/file_grouper.rb

Instance Method Summary collapse

Instance Method Details

#build_group_map(groups:, id_extractor:) ⇒ Hash

Builds a map from item ID to group index (0-based).

Parameters:

  • groups (Array<Array>)

    grouped items

  • id_extractor (Proc)

    callable that returns ID for an item

Returns:

  • (Hash)

    mapping of item ID to group index



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/export/file_grouper.rb', line 53

def build_group_map(groups:, id_extractor:)
  group_map = {}

  groups.each_with_index do |group, index|
    group.each do |item|
      group_map[id_extractor.call(item)] = index
    end
  end

  group_map
end

#group(items:, max_bytes:, size_extractor:) ⇒ Array<Array>

Groups items into batches that don’t exceed max_bytes.

Items larger than max_bytes will be placed in their own group. Order of items is preserved.

Parameters:

  • items (Array)

    items to group

  • max_bytes (Integer)

    maximum bytes per group

  • size_extractor (Proc)

    callable that returns size in bytes for an item

Returns:

  • (Array<Array>)

    array of groups, each group is an array of items



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

def group(items:, max_bytes:, size_extractor:)
  groups = []
  current_group = []
  current_size = 0

  items.each do |item|
    size = size_extractor.call(item)

    if current_group.any? && (current_size + size > max_bytes)
      groups << current_group
      current_group = []
      current_size = 0
    end

    current_group << item
    current_size += size
  end

  groups << current_group if current_group.any?
  groups
end