Form inputs in derived units for a schema in base units

As the title says: I’m looking to have form inputs in derived units (for instance, kilograms) for schema fields in base units (grams, for that example).

There will be many of these fields, as the application domain is simulation and control of physical systems. As a result, I’m looking for a way to do this without writing a lot of code for each field.

I can get halfway there with a custom Ecto.Type that converts derived → base when casting string → float to handle conversion on form submission, but it’s unclear how to handle the other half: converting base → derived to generate the HTML input.

One option for that part would be a custom input helper (to replace text_input for these fields): can anybody think of a simpler / shorter approach?

Yeah, that’s what I would do, plus you can use macros to generate several such helpers (probably for different units).

Another option is to have a custom Plug which you whitelist in your controllers which, when enabled, does conversion to some of the fields. How to filter those fields however sounds tricky.

Some of these might help:

I am working on parsing unit input of the form 1kg in a localised fashion so you could enter 1kg or 1 kilogram or 1 килограмм. That work will be finished over the weekend.

1 Like