pmartin8
pmartin8

Reputation: 1584

YAML configuration with validity range

I have a YAML file that contains some configuration for my application. Now, some configs need to change in time. For example:

For 2020 Values are:

tax:
    federal: 9
    provincial: 7

But for 2021, what we need is:

tax:
    federal: 9.5
    provincial: 7.5

It would be easy if I could only switch yml files through time, but the yaml file contains many configs that will change at different point in time. Plus, I'm only assigned 1 yml file to configure my application, so this is not really an option.

So my question is, what would be the cleanest way to represent this using YAML ?

The only way I can think of is the following, but I can see this going very messy.

tax:
    federal: [20200101-20201231]9;[20210101-20211231]9.5
    provincial:  [20200101-20201231]7;[20210101-20211231]7.5;

Upvotes: 1

Views: 1281

Answers (1)

flyx
flyx

Reputation: 39678

Your syntax is illegal, you would need to enclose that in quotes, parse it as single scalar, and post-process it.

I suggest to use YAML's tag system: You use a tag like !datedep to mark the values, e.g.:

tax:
    federal: !datedep { [20200101, 20210101, 20220101]: [9, 7.5] }
    provincial: !datedep { [20200101, 20210101, 20220101]: [7, 7.5] }

I give as value a YAML mapping with a single key-value pair. The key is a list of dates, building up the ranges in between. The value is the list of values which should be mapped to the ranges between the dates.

When loading the YAML, you have to provide a constructor for the tag !datedep. How this works depends on your implementation. The constructor should select the appropriate value based on the current date. You can use YAML anchors and aliases to reference duplicate date ranges, e.g.:

tax:
    federal: !datedep { &y2021 [20200101, 20210101, 20220101]: [9, 7.5] }
    provincial: !datedep { *y2021 : [7, 7.5] }

Upvotes: 1

Related Questions