Skip to content

Template based Conversions

macarci edited this page May 23, 2018 · 1 revision

Converter transformations helps to convert one record into another, usually from different data types but it can be from the same type. There are some options to configure a conversion, using templates like Liquid or Handlebars, by typing Ruby code or by configuring a Mapping Converter which is the most recent transformation feature.

Template and Ruby converter transformations both have in common a local variable named source, which allows to access the source record, for the Ruby template there’s also available a local variable target, which allows to configure the target record. The transformation code is responsable to configure the target record, for the examples described at Transformations

Liquid:

{
  "name": "{{source.name}} (converted)",
  "count": "{{source.items.count}}",
  "price": "{% eval source.items.inject(0) { |s, item| s + item.price } %}"
}

Ruby:

target.name = "#{source.name} (converted)"
target.count = source.items.count
target.total_price = source.items.inject(0) { |s, item| s + item.price }

they both configure the name of the target as the source record name followed by (converted), the target property count is the size of the association items in the source, and the total_price of the target is the sum of all the associated items prices.

A converter transformation can be coupled to an event via flow configuration. To execute the transformation every time a record is created just configure a flow choosing the transformation and a data event with a trigger for the created_at property when it is present. The present trigger for the property created_at only occurs when the record is created so the flow is executed just one time per source record. If it is desired the flow to be executed every time a record is updated it can be configured the data event with a trigger for the updated_at property when it changes. Now, the above conversion configurations codes will create a new record every time the flow is executed. To ensure the same target record is updated an id property value should be provided, for instance the same source id should works:

Liquid:

{
  "id": "{{source.id}}",
  "name": "{{source.name}} (converted)",
  "count": "{{source.items.count}}",
  "price": "{% eval source.items.inject(0) { |s, item| s + item.price } %}"
}

Ruby:

target.id = source.id
target.name = "#{source.name} (converted)"
target.count = source.items.count
target.total_price = source.items.inject(0) { |s, item| s + item.price }
Clone this wiki locally