Transform nested array of hashes (dry-transformer)


Getting to grips with dry-transformer, using it to convert my ActiveRecord objects into a hash for an API call I’m going to make. Seems to do what I need apart from when things get a bit more complex.

This is my current input into a mapper class I’ve created

{ id: 1, user_id: 2, line_items: [{order_id: 1, desc: "hello"}, {order_id: 1, desc: "world"}] }

In my mapper i’m renaming the id field to ShipmentId and user_id to CustomerId.

Now I want to transform the array of line_items. I want to rename them to ShipmentLines (easy) and I want to go over each hash in the array and rename order_id to ShipmentId (finding this difficult).

Here’s my current mapper class:

define! do
  rename_keys id: :ShipmentId
  rename_keys user_id: :CustomerId
  rename_keys line_items: :ShipmentLines

I wanted to add a map_array(:ShipmentLines) do end block in the define block but that doesn’t seem to be working. I get argument errors.

Does anyone know how to transform a hash which also has a key with an array of hashes (line_items in this case)? Thanks!

Edit: Got it working by separating it into a new mapper class, not sure if this is the correct way to do it, or if there’s a better way.

map_value :ShipmentLines, -> lines do { |line_item| }

I believe this would work:

map_value :ShipmentLines do
  map_array do
    # do your stuff

Thanks will give it a go.