-
Notifications
You must be signed in to change notification settings - Fork 129
Ruby Templates
The simplest way to configure a Ruby template is by invoking the build-in format methods (to_hash, to_json, share_hash, to_xml, to_edi) on the local variable source
, which represent the source record the template is being applied to. For example for a JSON template just the following code:
source.to_json
there are some options that can be used for the build-in methods, perhaps the template should be pretty JSON formatted, or some properties must be excluded:
source.to_json(pretty: true, ignore: 'id')
For the previous example where a data type is supposed to have the properties name and items where items is an association the above code will generate a JSON like this:
{
"name": "A",
"items": [
{
"name": "A1",
"price": 1.0
},
{
"name": "A2",
"price": 2.0
},
{
"name": "A3",
"price": 3.0
}
]
}
The build-in format methods use the data type structure to generate the template, by default all properties are included. Of course a JSON template with completely different entries can be configured by typing the appropriated ruby code. For example:
{
name: source.name,
count: source.items.count,
price: source.items.inject(0) { |s, item| s + item.price }
}
will produce the following JSON
{
"name": "A",
"count": 3,
"price": 6.0
}