Skip to content

Instantly share code, notes, and snippets.

@cored
Created May 22, 2018 15:35
Show Gist options
  • Save cored/d8885f9514f08cc488634218e9ba741e to your computer and use it in GitHub Desktop.
Save cored/d8885f9514f08cc488634218e9ba741e to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
module Groupments
class GroupShipments
def self.call(shipments:)
new(shipments: shipments).call.grouped_shipments
end
attr_reader :grouped_shipments
def initialize(shipments:)
@shipments = shipments
end
def call
group_shipments
self
end
private
attr_reader :shipments
def group_shipments
@grouped_shipments = (non_groupable_shipments +
grouped_courier_shipments +
grouped_parcel_shipments
).compact
end
def non_groupable_shipments
shipments - courier_shipments - groupable_parcel_shipments
end
def grouped_courier_shipments
[courier_shipment]
end
def grouped_parcel_shipments
[parcel_shipment_without_hard_goods]
end
def parcel_shipment_without_hard_goods
build_shipment_items_for(groupable_parcel_shipments)
end
def courier_shipment
build_shipment_items_for(courier_shipments)
end
def courier_shipments
@_courier_shipments ||= shipments.select(&:courier?)
end
def groupable_parcel_shipments
@_groupable_parcel_shipments ||= shipments.select do |shipment|
shipment.parcel? && !shipment.hard_goods?
end
end
def build_shipment_items_for(shipments)
return if shipments.empty?
shipments.first.tap do |shipment|
shipment.shipment_items = shipments.flat_map(&:shipment_items)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment