Class: ParcelsChallenge::ShipmentGrouper

Inherits:
Object
  • Object
show all
Defined in:
lib/parcels_challenge/shipment_grouper.rb

Instance Method Summary collapse

Constructor Details

#initialize(file_path, output_file_path = 'shipment_assignment.csv', shipment_max_weight = 2311, validate_csv = false) ⇒ ShipmentGrouper

Returns a new instance of ShipmentGrouper.



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

def initialize(
  file_path,
  output_file_path = 'shipment_assignment.csv',
  shipment_max_weight = 2311,
  validate_csv = false
)
  @shipment_max_weight = shipment_max_weight
  @validate_csv = validate_csv
  @output_file_path = output_file_path
  @file_path = check_file(file_path)
end

Instance Method Details

#perform!Object



18
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
54
55
56
57
# File 'lib/parcels_challenge/shipment_grouper.rb', line 18

def perform!
  """
  The perform method is where the magic happens. I've mentally
  divided this method into the grouping of the clients, assignment
  of the clients into shipments base on previous groupings and
  generating the output file.
  I tried to use CSV's #foreach method as much as possible since
  it doesn't load the full file into memory. This should be performant
  in terms of memory but as files get larger and more shipments are
  possible, so will the amount of client_shipment_assignments grow.
  """
  grouped_sum = {}

  CSV.foreach(file_path, headers: true) do |parcel|
    Integer(parcel['weight']) rescue raise 'Weight is not an Integer'
    if grouped_sum[parcel['client_name']].nil?
      grouped_sum[parcel['client_name']] = parcel['weight'].to_i
    else
      grouped_sum[parcel['client_name']] += parcel['weight'].to_i
    end
  end

  client_shipment_assignment = assign_client_to_shipment(grouped_sum)

  CSV.open(output_file_path, 'wb') do |csv|
    csv << %i[parcel_ref client_name weight shipment_ref]
    CSV.foreach(file_path, headers: true) do |parcel|
      csv << [
        parcel['parcel_ref'],
        parcel['client_name'],
        parcel['weight'],
        client_shipment_assignment[parcel['client_name']]
      ]
    end
  end

  puts "Output file generated at: #{Pathname.pwd.to_s}/#{output_file_path}"

  output_file_path
end