Authorize allowed values with assignable_values
All our projects have enum-like requirements like this:
- An attribute value must be included in a given set of values.
- The list of allowed values must be retrievable in order to render
- Each value has a humanized label.
- Sometimes there is a default value.
Most of the time, this requirement is also needed:
- The list of assignable values depends on the user who is currently signed in.
In our past projects there are many different solutions for these related requirements, e.g.
ChoiceTrait, methods like
available_states, helper methods to render option tags, and so on. Unfortunately each of these solutions is limited in its own way, so it was time to come up with a standard solution.
assignable_values is the new way
We have now updated/created two gems that implement the requirements above using the best practices we know of:
- assignable_values: ActiveRecord macro to restrict the values that may be assigned to an attribute. Think of it as "enums on vitamins".
- consul: Our standard authorization solution. Optionally integrates with the assignable_values gem so lists of assignable values can be defined in a
Powerinstead of in an ActiveRecord model.
This is the way we want to implement the requirements above in most of our future projects. You should migrate existing projects to assignable_values if you run into the limits of our previous approaches (e.g.
ChoiceTrait cannot be internationalized).
Please read the assignable_values README to familiarize yourself with the new solution.
There is a custom RSpec matcher.