Description
Let's add support for choices on string model and schema fields.
Rationale
Marten presently supports string fields for persisting and validating string values, and enum fields for restricting values to a Crystal Enum. However, there is no lightweight way to restrict a string field to a predefined set of values without defining a dedicated enum class.
To palliate this, let's introduce a choices option for string fields (similar to Django's choices), allowing allowed values to be specified inline at field definition time.
Usage
Model fields
class Article < Marten::Model
field :id, :big_int, primary_key: true, auto: true
field :status, :string, max_size: 20, choices: ["draft", "published", "archived"]
end
article = Article.new(status: "draft")
article.valid? # => true
article.status = "invalid"
article.valid? # => false
Schema fields
class ArticleSchema < Marten::Schema
field :status, :string, choices: ["draft", "published", "archived"]
end
Restrictions
- The
choices option should only be available on string fields.
- All choice values should respect the field's
max_size constraint.
- Invalid values should fail validation with a clear error message.
Description
Let's add support for
choiceson string model and schema fields.Rationale
Marten presently supports
stringfields for persisting and validating string values, andenumfields for restricting values to a CrystalEnum. However, there is no lightweight way to restrict a string field to a predefined set of values without defining a dedicated enum class.To palliate this, let's introduce a
choicesoption for string fields (similar to Django'schoices), allowing allowed values to be specified inline at field definition time.Usage
Model fields
Schema fields
Restrictions
choicesoption should only be available onstringfields.max_sizeconstraint.