How to make attr accept only a set of values in LiveView 0.18?

Phoenix LiveView 0.18 is coming with some really cool DX improvements. One of them is the declarative assigns with attr macro. phoenix_live_view/ at master · phoenixframework/phoenix_live_view (
more details about the attr macro are found here phoenix_live_view/phoenix_component.ex at f0722958a5deb0c0f73b798e4bcfc2efa0b832f2 · phoenixframework/phoenix_live_view · GitHub
It actually is a beautiful addition to Function Components. What I could not understand from the documentation is -
how do I make the attribute accept values from only a set of values? For example, my button component has an attribute color - which can only accept values “blue”, “green” and “red”. How to define the attr?

1 Like

You would have to pack that information into a struct as there is no enum type at the moment.

Or maybe a list and document thoroughly

1 Like

To quote from the attr docs:

LiveView does not perform any validation at runtime. This means the type information is mostly used for documentation and reflection purposes.

Checking for membership would be a runtime validation, so it is not supported.

My guess is that we’ll quickly see some runtime validation libraries pop up after 0.18 is released. It makes sense to me and is in keeping with other decisions that they’ve made the feature a minimal, general implementation and left enhancement up to the individual.

1 Like